使用Jest进行react测试react
npm install --save-dev jest
npm
在package.json文件中添加json
{
"scripts": {
"test": "jest"
}
}
复制代码
以后就可使用npm run test
跑测试了api
若是须要babel的话,还须要安装babel并进行配置数组
安装babel相关依赖: npm i -D babel-jest @babel-core @babel/preset-env
promise
并建立.babelrc文件,因为须要使用react,因此也添加了react须要的相关配置bash
{
"presets": [
"@babel/env",
"@babel/react"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-runtime"
]
}
复制代码
跟其余的不少测试框架同样,jest也有不少匹配器供咱们去使用,匹配器那么多hhhh。。。看上去就是它自己要表达的意思。babel
toBe
test exact equality框架
toEqual
recursively checks every field of an object or array. 递归检查判断dom
toBeCloseTo
用来比较小数,避免浮点数偏差(0.1 + 0.2).toBeCloseTo(0.3)
toBeNull
toBeUndefined
toBeDefined
toBeTruthy
toBeFalsy
(There are only six falsey values in JavaScript: undefined
, null
, NaN
, 0
, ""
, and false
.)
toBeGreaterThan
toBeGreaterThanOrEqual
toBeLessThan
toBeLessThanOrEqual
toMatch
正则匹配。
toContain
判断数组中是否包含指定项。
.toHaveProperty(keyPath, value)
判断对象中是否包含指定属性。
toThrow
判断是否抛出指定的异常。
toBeInstanceOf
判断对象是不是某个类的实例,底层使用 instanceof
。
全部的方法均可以使用.not取反 好比 (0.1 + 0.2).not.toBeCloseTo(0.4)
异步测试的方法也不少
关于异步测试,官网说的比较清楚,这里就说一些须要注意的点吧
Promse —— resolves && rejects
Jest will wait for that promise to resolve .
If the promise is rejected, the test will automatically fail.
If you expect a promise to be rejected use the .catch method
复制代码
在使用resolves或者rejects对Promise进行测试的时候,须要把整个断言做为返回值返回,若是忘了return
,在 fun
函数返回的这个 promise 变为 resolved 状态、也就是then() 执行以前,测试就已经被视为完成了。
test('when it resolved', () => {
return expect(fun()).resolves.toBe('...');
});
复制代码
done()
若是使用回调函数处理异步,好比fun函数再处理完成时须要调用callback(),若是直接在测试中写以下代码,可是Jest测试在执行结束后才会完成,那么这个测试时时不会工做的。
这个时候使用单个参数调用 done
,而不是将测试放在一个空参数的函数。 Jest会等done
回调函数执行结束后,结束测试。
test('...', done => {
function callback(data) {
expect(data).toBe('...');
done();
}
fun(callback);
});
复制代码
async && await
能够把resolves/rejects 和 async/await配合使用
test('success', async () => {
await expect(fun()).resolves.toBe('...');
});
test('error', async () => {
await expect(fun()).rejects.toThrow('error');
});
复制代码
须要测试react的时候,须要安装npm i -dev react-test-renderer
去render snapshot
render一个组件以后,生成的snapshot就是对这个组件的节点的渲染结果,在使用npm run test
以后会生成名为__snapshots__
的文件夹,其中的文件格式为component.test.js.snap,snapshot文件也须要提交到代码库中。
在下一次运行测试的时候,新渲染的结果会和以前的snapshot进行比较,若是不一样则测试失败,若是变更符合预期,想要更新snapshot,能够经过npm run test:update
来操做。
某些状况下,咱们须要测试某一个component中的一个节点有没有被渲染或者节点的内容是否符合预期
在测试节点的时候,咱们能够搭配使用一些testing library,固然使用以前也须要安装——npm i --dev @testing-library/react
mock相关依赖和组件
mock module
在测试节点以前,若是当前组件中引用了其余的模块,须要先mock组件依赖的模块jest.mock('../fileName');
mock component
若是须要测试的组件中还包括其余组件,为了保证不受其余组件的影响,这个时候咱们也须要mock组件引入的其他组件,
好比在Header组件中引用了Context组件,那么就须要mock Context组件,好比Context中为一个div,咱们能够直接将Context mock为一个div,其中的内容并不重要
jest.mock('../Context', () => {
const MockContext = () => <div>Some Context</div>;
return MockContext;
});
复制代码
测试组件节点渲染
在mock完相关的依赖以后,就能够对自身组件进行测试了
例如在Header中,咱们须要测试是否渲染了一个Button
//Header.js
<Button data-testid="button">
Button Context
</Button>
复制代码
//Header.test.js
import {render} from '@testing-library/react';
renderHeader = render(<Header />); it('should show button', () => { expect(renderHeader.getByTestId('button')).toBeInTheDocument(); }); 复制代码
在这个测试中render(<Header />)
是使用testing library的render方法渲染出Header组件
renderHeader.getByTestId('button')
是testing library中的query方法,更多的query方法能够看这里
可是,若是Header中并无这个button的话,使用getByTestId
会报错,这是由于在 testing library中的query方法中,全部的getBy方法都返回找到的第一个节点,并在没有匹配到或者匹配到多个时抛出error,这个时候就须要使用queryBy方法,即queryByTestId
queryBy方法返回找到的第一个节点并在没有找到时返回null。
测试组件event
例如咱们要测试点击Header组件中的button以后须要发生的事情,这个时候就须要模拟点击事件
fireEvent.click(renderHeader.getByTestId('button'));
更多的事件跳这里