Testing with Jest - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
Full featured test framework:
- Test framework
- Assertion
- Mock
https://facebook.github.io/jest/
npm install --save-dev jest babel-jest
-
beforeEach
-afterEach
-beforeAll
-afterAll
-
describe
: group of test -
test
: define a single test
- expect
- Create mock function:
const mock = jest.fn()
- Return pre-determined values:
-
mock.mockReturnValue(3)
-mock.mockReturnValueOnce(3)
- Set simple implementation:
-
sum.mockImplementation((a, b) => 3);
-sum.mockImplementationOnce((a, b) => 3);
- Verify how many times function has been called; with what arguments:
-
expect(mock).toBeCalledWith(1, 2)
-mock.mock.calls
: array of arguments which this method was called with - Track objects instantiated from a mock with the 'new' keyword:
mock.mock.instances
Jest can mock a module with command jest.mock('<module name>')
. After that, require('<module name>')
(or import) will return the mock module.
This is good for mocking dependent modules of module under test.
With import
, a single variable is used for the mock module. Each test will add data into mock module. We may need to use mock.mockReset()
in beforeEach
for resetting the data.
A mock version for a module could be placed in __mocks__
folder which is placed in the same folder of the real module.
Jest will use that mocked module implementation instead of its default implementation.
spy = jest.spyOn(object, '<method>')
https://facebook.github.io/jest/docs/jest-object.html#jestspyonobject-methodname
- Track calls to object.method().
- Mock the object.method with
spy.mockImplementation(() => customImplementation)
jest
Run test and give the code coverage report
jest --coverage
Watch the file changes and run tests
jest --watch
There are some options of tests to be run:
- Run all tests.
- Run tests which are affected by the changes.
- Run selected tests (Pattern).
- Description: With webpack, we can import css file and image file. However, jest cannot run with them.
- Solution: Configure jest to use mock files for css files or image files:
"jest": {
"moduleNameMapper": {
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
}
Add styleMock.js
:
export default {};