-
Notifications
You must be signed in to change notification settings - Fork 2
Test react with Jest and Enzyme.
Jest is a Testing framework, It provides the full-featured tools to test react UI component. In jest docs, it uses react-test-renderer to render react in the node environment. Also, we can use Enzyme from Airbnb to render react component.
Enzyme provides three main root level API shallow, mount, render
How it works? in xxx.test.jsx under __test__ folder , we will wirte our test code to simulate real world code. Then we run jest, the first run will generate the snapshot file for your test file, the first generated shanpshot file can be checked into source control, So if your team code review had passed, it will be a reference for your next run, otherwise the source code shuold be revise to satisfy code review. The next run will generate a new snapshot file, and jest will compare it with the older version snapshot file, if they matched, the test passed. otherwise, jest will print the diffs.
jest.config.js in the root directory is the default configuration file. it looks like this
module.exports = {
setupFiles: ["<rootDir>/scripts/jest/setupTests.js"],
"verbose": true,
snapshotSerializers: ["enzyme-to-json/serializer"],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
'json',
'node',
],
}Jest is running in node environment, But our source code is written in typescript with import/export API, So we should let jest knows how to use babel to transpile source code, babel-jest do the job. Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the transform configuration option
// jest.config.js
module.exports = {
transform: {},
}Current .babelrc uses @babel/preset-env with option modules: false, this let webpack to do the bundle job. But in jest world, no webpack used, So Babel should do the bundle job. So in the test environment, we should set modules: commonjs, that's why move .babelrc to babel.config.js
// babel.config.js
const basic = {
"presets": [
["@babel/preset-env", {
"debug": true,
"modules": false
}],
["@babel/preset-react"],
["@babel/preset-typescript"]
],
"plugins": [
["@babel/plugin-transform-runtime"],
["@babel/plugin-proposal-object-rest-spread"],
["@babel/plugin-proposal-class-properties"]
]
}
module.exports = function babel(api) {
if(api.env('test')) {
basic.presets[0][1].modules = 'cjs'
}
return basic;
}Refer to Handling Static Assets, stylesheet and image files aren't particularly useful in tests so we can safely mock them out, So some mock file should be added
// jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/scripts/jest/__mocks__/fileMock.js",
"\\.(css|styl)$": "<rootDir>/scripts/jest/__mocks__/styleMock.js"
}
}// __mocks__/styleMock.js
module.exports = {};
// __mocks__/fileMock.js
module.exports = 'test-file-stub';