Running tests using standalone Jest

The test script from react-scripts that you just learned about in the previous section is a great tool to have running in the background while you're building your application. It gives you immediate feedback as you implement components and unit tests.

Other times, you just want to run all tests and have the process exit as soon as the result output is printed. For example, if you're integrating Jest output into a continuous integration process or if you just want to see test results run once, you can run Jest directly.

Let's try running Jest on its own. Make sure that you're in your project directory still and that you've stopped the npm test script from running. Now just run:

jest

Rather than running Jest in watch mode, this command simply attempts to run all of your tests, prints the result output, and then exits. However, there seems to be a problem with this approach. Running Jest like this results in errors:

FAIL  src/Repeat.test.js
  Test suite failed to run
    
   04/my-react-app/src/Repeat.test.js: Unexpected token (7:18)
        5 | it('renders the Repeat component', () => {
        6 |   const div = document.createElement('div');
      > 7 |   ReactDOM.render(<Repeat times="5" value="test"...
          |                   ^
        8 | });

This is because the test script from react-scripts sets up a lot of things for us, including all of the Jest configuration necessary to parse and execute JSX. Given that we have this tool available to us, let's just use it rather than go through the headache of trying to configure Jest from scratch. Remember, your goal is to run Jest once—not in watch mode.

It turns out that the test script from react-scripts is ready to handle continuous integration environments. If it finds a CI environment variable, it won't run Jest in watch mode. Let's try this out by exporting this variable:

export CI=1

Now when you run npm test, everything works as expected. The process exits when everything is finished:

PASS  src/Text.test.js
PASS src/App.test.js PASS src/Repeat.test.js Test Suites: 3 passed, 3 total Tests: 3 passed, 3 total Snapshots: 0 total Time: 1.089s Ran all test suites.

You can then unset this environment variable when you're done:

unset CI 

Most of the time, you'll probably just use Jest in watch mode. But in case you need to quickly run your tests in a short-lived process, you can temporarily enter continuous integration mode.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.80.45