Jest

April 30, 2024

What is Jest?

Jest is a test automation framework for Javascript and Typescript.  Jest is generally used for unit testing, meaning it tests parts of a codebase in isolation, rather than integration testing where the parts are combined and tested to see how they work together (though Jest can be used for both). Jest makes it easy to write and manage standardized Javascript tests for your codebase. Jest works hand in hand with your CI (Continuous Integration) system to ensure tests are reliable and repeatable across team members and environments.

Enabling XML Output

Configure Jest to produce JUnit XML output. 

1npm install --save-dev jest-junit

Update your Jest config (jest.config.json or similar file) to add jest-junit as a reporter.

jest.config.json

1{
2  "reporters": [ "default", "jest-junit" ]
3}

With this configuration, Jest will output a junit.xml file in the working directory. To further configure the reporter, consult the detailed documentation on GitHub.

Test Suite naming

The jest-junit reporter will automatically fill in values for the <testcase/> and <testsuite/> name and class attributes using the description parameters to the tests. The testsuites.name is set to jest tests by default.

To make it easier to debug, it is also useful to include the name of the file that the failing test is in. You can do this by adding this to the jest.config.json file.

1 "addFileAttribute": "true"

For example, this test:

1describe('addition', () => {
2  describe('positive numbers', () => {
3    it('should add up', () => {
4      expect(1 + 2).toBe(3);
5    });
6  });
7});

would produce output that looks like this:

1<testsuites name="jest tests">
2  <testsuite name="addition">
3    <testcase classname="addition positive numbers should add up" 
4              name="addition positive numbers should add up"
5              file="src/math.test.js"
6              >
7    </testcase>
8  </testsuite>
9</testsuites>

The default attributes can be changed using jest-junit configuration settings

Handling Retries

By default, Jest will not retry tests. The developer must restart the tests manually.  To have Jest automatically retry failed tests use the retryTimes setting. Ex:

1jest.retryTimes(3);
2test('will fail', () => {
3   expect(true).toBe(false);
4});

If you need to retry a lot of tests that is a strong indicator that you may have flaky tests. These are tests that sometimes pass and sometimes fail, slowing down your development process. You can get early access to Trunk’s new Flaky Tests tool to manage these types of tests better.

Other Configuration

See an example of running Jest inside of a GitHub action here.

Jest is highly customizable. See more at the Jestjs.io homepage.

Try it yourself or
request a demo

Get started for free

Try it yourself or
Request a Demo

Free for first 5 users