第一步,我们需要安装所需依赖包进行支持:
npm install @babel/plugin-transform-react-jsx @testing-library/jest-dom @testing-library/react jest --save-dev
第二步,我们需要在babel.config.js
中加入jsx
转换:
module.exports = {
presets: [['babel-preset-env', { targets: { node: 'current' } }]],
++ 'plugins': ['@babel/plugin-transform-react-jsx'] // 需要加入的配置
}
第三步,我们需要新建jest.config.js
来配置jest
:
// 根目录下创建: jest.config.js
// 配置文档
//https://jestjs.io/docs/zh-Hans/configuration
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
'\\\\node_modules\\\\'
],
// An array of file extensions your modules use
moduleFileExtensions: [
'js',
'jsx',
],
// A list of paths to directories that Jest should use to search for files in
roots: null,
// The test environment that will be used for testing
// testEnvironment: 'node',
testEnvironment: 'jsdom',
// The glob patterns Jest uses to detect test files
testMatch: [
'**/__tests__/**/*.js?(x)',
//"**/?(*.)+(spec|test).js?(x)"
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: [
'\\\\node_modules\\\\'
],
// A map from regular expressions to paths to transformers
transform: {
'^.+\\.js$': 'babel-jest',
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
transformIgnorePatterns: [
'\\\\node_modules\\\\'
],
// moduleNameMapper: {
// '\\.(css|less)$': 'identify-obj-proxy'
// }
}
单元测试文件统一放在
src/__tests__
目录下,如果需要修改,请修改jest.config.js
中的testMatch
下的规则
但是我们一般会在jsx
中引入了css
或less
样式,所以为了jest
支持less
,我们还需要额外增加配置来支持less
。
我们需要安装jest-less-loader
来让jest
识别less
:
npm install jest-less-loader --save-dev
然后在jest.config.js
中增加以下配置:
module.exports = {
...
transform: {
'^.+\\.js$': 'babel-jest',
++ '\\.(less|css)$': 'jest-less-loader' // 支持less
},
...
}
这个时候运行jest
进行单元测试就可以了。
案例:
src/__tests__/tab-test.js
import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-dom/test-utils'
import Tabs from '../components/Tab/Tabs.js'
import TabPane from '../components/Tab/TabPane'
describe('tab', ()=>{
it('render the tab content', function () {
const tab = TestUtils.renderIntoDocument(
<Tabs classPrefix={'tabs'} defaultActiveIndex={0} className="ui-tabs">
<TabPane order={0} tab={'Tab 1'}>第一个Tab里的内容</TabPane>
<TabPane order={1} tab={'Tab 2'}>第二个Tab里的内容</TabPane>
<TabPane order={2} tab={'Tab 3'}>第三个Tab里的内容</TabPane>
</Tabs>
)
const tabNode = ReactDOM.findDOMNode(tab)
expect(tabNode.querySelectorAll('.tabs-tab').length).toEqual(3)
expect(tabNode.querySelectorAll('.tabs-tab')[0].classList.contains('tabs-active')).toBe(true)
})
})