React ~ Testing ~ Jest - rohit120582sharma/Documentation GitHub Wiki

Jest is a JavaScript unit testing framework which is a super version of Jasmine.

Jest is a framework and not a library. It comes with a test runner, assertion library, and good mocking support. A pretty comprehensive all-in-one testing framework which is kind of equivalent to Mocha (test runner) + Chai (assertion library) + Sinon (spies, mocks) + Istanbul (coverage).

Place your tests in a tests folder, or name your test files with a .spec.js or .test.js extension. Whatever you prefer, Jest will find and run your tests.

References



Setup

Installation

$ npm i --save-dev jest jest-dashboard

# If using "React-Native":
$ npm i --save-dev jest-react-native

# If using babel, install as below and don't forget to add a ".babelrc" file in your project's root folder.
$ npm i --save-dev babel-jest babel-core regenerator-runtime

# If using enzyme:
$ npm i --save-dev jest-enzyme

Configuration

/**
 * jest.config.js
 * Remove jest configuration from package.json and create this config file
 */
module.exports = {
    preset: "react-native", // Only if using react-native
    verbose: true,
    setupTestFrameworkScriptFile: "<rootDir>src/test/setupTests.js",
    testPathIgnorePatterns: [
        "/node_modules/",
        "/src/modules/",
        "/src/common/utils/"
    ],
    "coveragePathIgnorePatterns": [
        "/node_modules/",
        "/src/modules/",
        "/src/common/utils/"
    ],
    transform: {
        "^.+\\.js?$": "babel-jest"
    },
    automock: false
}

Run

$ npm run jest

# Watch mode
$ npm run jest --watch

# Coverage Reporting. Also check "coverage/lcov-report/index.html" file for report
$ npm run jest --coverage


Jest API

The Jest API focusses more on the ability to define tests, make assertions, and create mocks.

  • describe: defines a test suite.
  • it: defines a test.
  • beforeEach: defines an entry hook before running each test.
  • expect: makes an assertion.
  • jest.fn(): creates a mock function.

Several methods are available for assertions.

  • toEqual: checks if two objects have the same value.
  • toBe: checks if two objects have the same value and type.
  • toBeDefined: checks if the object is defined.
  • toContain: checks if an item is present in a list.
  • toBeCalled: checks if a mock function is called.

There are useful methods on the mock.

  • mockImplementation: provides an implementation for the mock function.
  • mockReturnValue: returns a value when the mock function is called.
⚠️ **GitHub.com Fallback** ⚠️