Skip to content

Instantly share code, notes, and snippets.

@SanthoshRaju91
Last active May 16, 2018 05:15
Show Gist options
  • Save SanthoshRaju91/904dee4f84ebb2f94399b22dccd588cc to your computer and use it in GitHub Desktop.
Save SanthoshRaju91/904dee4f84ebb2f94399b22dccd588cc to your computer and use it in GitHub Desktop.
Jest configuration

This is the configuration steps to configure Jest testing framework for react applications.

  1. npm install --save-dev jest

It loads all of the dependencies to work with jest, so you don't need to figure them out individually again.

  1. Add script for jest in package.json
{
  ....
  "scripts": {
    "test": "jest"
  }
}

Now running the npm run test script, this will co-locate tests patterns like __tests__

  1. If you have any tests, and while running you will get "Unexpected token import", because webpack supports ES6 modules, for treeshaking.

So you need to specify that in the .babelrc file, babelrc is just a json file, you can make it a .js file as well, so that you can configure.

In package.json, you need to specify the babel presets to look for the appropriate file extension with holds the babel configuration.

{
  ...
  "babel": {
    "presets": "./.babelrc.js"
  }
}

and in the .babelrc.js add the configuration.

const isTest = String(process.env.NODE_ENV) === 'test'

module.exports = {
  presets: [['env', {modules: isTest ? 'commonjs' : false}]]
}

NODE_ENV is implicitly set by the Jest framework to 'test'. Once this is set, babel transplies the ES6 modules to commonjs ( default module syntax for node) which jest can understand and the run the test files.

  1. By default Jest provides the JSDOM as testing utilities, this is pretty heavy in terms of running only JS related test files which has nothing to do with the DOM.

Disable this in the package.json configuration

{
  ...
  "jest": {
    "testEnvironment": "jest-environment-node"
  }
}

OR

```javascript
{
  ...
  "jest": {
    "testEnvironment": "ode"
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment