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

To integrate cleanly with CI systems and other testing tools, Jest can be configured to produce JUnit XML output. Add the jest-junit package to your codebase and modify the config file (jest.config.json or similar file) to add it as a reporter.

1npm install --save-dev jest-junit

jest.config.json

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

Now you can run Jest from the command line with 

1jest

And from within your CI system with

1jest --ci --reporters=default --reporters=jest-junit

Test Suite naming and output

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. 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    </testcase>
6  </testsuite>
7</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 Testing Frameworks

Jest is only one of several popular testing frameworks for Javascript & Typescript. You might also want to look at

Try it yourself or
request a demo

Get started for free

Try it yourself or
Request a Demo

Free for first 5 users