Skip to content

Test Your Plugin

Shane McLaughlin edited this page Jul 11, 2023 · 13 revisions

Our Testing Philosophy

We (the Salesforce CLI dev team) use two types of tests to ensure the quality of our plugins:

  1. Unit tests
  2. Non-unit-tests (NUTs)

We generally use unit tests to test library-level code and NUTs to test command-level code. With this philosophy, unit tests ensure the functionality of the classes and functions consumed by a command, and then NUTs ensure that the command itself works as expected.

You can of course test your plugin however you want, although we recommend you give our philosophy a try. The next sections describe in more detail how we use NUTs and unit tests.

Unit Tests

For library-level code, we like to write unit tests using mocha to run the tests and nyc for test coverage. You're not limited to this framework - you're free to use whatever NodeJS-compatible testing framework works best for you, such as jest.

Here are some examples of how we leverage unit tests across our codebases:

Unit Tests for Commands

While we strongly recommend writing NUTs (see below) for command-level unit tests, it is possible to do this. Here's a brief example:

import { expect } from 'chai';
import { TestContext } from '@salesforce/core/lib/testSetup';
import { stubSfCommandUx } from '@salesforce/sf-plugins-core';
import { DoStuff } from '../../../../src/commands/do/stuff';

describe('do:stuff', () => {
  const $$ = new TestContext();
  let sfCommandUxStubs: ReturnType<typeof stubSfCommandUx>;

  beforeEach(async () => {
    // stub SfCommand's ux methods so that command output is suppressed
    // and so that you can assert that certain methods were called with
    // the correct args.
    sfCommandUxStubs = stubSfCommandUx($$.SANDBOX);
  });

  it ('should do awesome things', async () => {
    // run the command using the static run method
    const result = await DoStuff.run(['--flag1', '--flag2'])

    expect(result).to.be.ok;
    expect(sfCommandUxStubs.log.firstCall.firstArg).to.equal('hello world');
  });
})

Here are some examples of how we write command-level unit tests across our codebases:

See the stubUx docs for built-in stubs for spinner/table/warning/prompt/etc

Non-Unit-Tests (NUTs)

We use non-unit-tests, known as NUTs, for command-level testing. As the name implies, NUTs are automated tests that aren't unit tests. NUTs typically include integration, functional, UI, and smoke tests that require a system outside your code to accomplish the test.

This style of testing allows you to use an isolated Salesforce project and file system against production Salesforce orgs. As a result, you can write tests that mimic your customers' environments as closely as possible. And you don't have to write and maintain mocked API responses anymore.

Check out the examples in the @salesforce/cli-plugins-testkit repo.

Clone this wiki locally