Running A Single Test With Jest

Sometimes it's good to be singled out.

Introduction

One thing that happens from time to time is wanting/needing to run just a single test. You’ll often want this level of granularity when working on a given test. Why keep running the whole suite, or even a single file of tests? The time difference can be immense.

Accomplishing this with Jest comes down to two things: first specifying the file the test is in, and secondly by marking the specific test.

Specifying the File

We need to first limit the running of tests to only the file that contains our singled out test is in. We will assume you have some flavor of jest in your npm test command. We want to specify the file the test is in. Here’s an example of how:

npm test -- shared/photo.spec.js

Note: The -- parameter after npm test passes the CLI parameters to the original jest command defined in the package.json script.

Now we have limited the run to just one file. But how do we limit it further, to just a single test?

Marking the Particular Test

Now, inside the file we are limiting let’s mark the particular test with .only in order to single it out.

For example:

  test.only('throws an error if no DataURL is provided', async () => {
    try {
        await Photo.uploadDataUrl()
    } catch (error) {
        expect(error.message).toBe('No Data URL provided');
    }
  });

And that’s it. Run the command again and you should see an output like:

Test Suites: 1 passed, 1 total
Tests:       1 skipped, 1 passed, 2 total
Snapshots:   0 total
Time:        1.829 s, estimated 2 s

Conclusion

As you can see, it’s pretty easy to run a single test using Jest. The TLDR is:

  1. npm test -- shared/photo.spec.js.
  2. Add .only to the test.

Erik August Johnson is a software developer working with JavaScript to build useful things. Follow them on Twitter.