本文根据 Devhints / Jest 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2020-06-17。
快速概览 Jest,这是一个针对 Node.js 的测试框架。本指南适用于 Jest v20 版本。
测试
快速入门
npm install --save-dev jest babel-jest
/* Add to package.json */
"scripts": {
"test": "jest"
}
# Run your tests
npm test -- --watch
参见: 入门
编写测试
describe('My work', () => {
test('works', () => {
expect(2).toEqual(2)
})
})
参见: describe(), test(), expect()
BDD 语法
describe('My work', () => {
it('works', () => {
···
})
})
it 是……的别名 test。参见: test()
设置 (Setup)
beforeEach(() => { ... })
afterEach(() => { ... })
beforeAll(() => { ... })
afterAll(() => { ... })
参见: afterAll() 及更多内容
聚焦测试
describe.only(···)
it.only(···) // alias: fit()
参见: test.only
跳过测试
describe.skip(···)
it.skip(···) // alias: xit()
参见: test.skip
可选标志
| 标志 | 说明 |
|---|---|
--coverage | 查看测试覆盖率摘要 |
--detectOpenHandles | 查看未关闭端口的摘要 |
--runInBand | 依次运行所有测试 |
断言 (Expect)
基本断言
expect(value)
.not
.toBe(value)
.toEqual(value)
.toBeTruthy()
请注意 toEqual 执行的是深度相等性检查。请参阅: expect()
快照
expect(value)
.toMatchSnapshot()
.toMatchInlineSnapshot()
请注意 toMatchInlineSnapshot() 需要为项目配置 Prettier。请参阅: 内联快照
错误
expect(value)
.toThrow(error)
.toThrowErrorMatchingSnapshot()
布尔值
expect(value)
.toBeFalsy()
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toBeDefined()
数字
expect(value)
.toBeCloseTo(number, numDigits)
.toBeGreaterThan(number)
.toBeGreaterThanOrEqual(number)
.toBeLessThan(number)
.toBeLessThanOrEqual(number)
对象
expect(value)
.toBeInstanceOf(Class)
.toMatchObject(object)
.toHaveProperty(keyPath, value)
对象
expect(value)
.toContain(item)
.toContainEqual(item)
.toHaveLength(number)
字符串
expect(value)
.toMatch(regexpOrString)
其他
expect.extend(matchers)
expect.any(constructor)
expect.addSnapshotSerializer(serializer)
expect.assertions(1)
更多功能
异步测试
test('works with promises', () => {
return new Promise((resolve, reject) => {
···
})
})
test('works with async/await', async () => {
const hello = await foo()
···
})
返回 Promise,或使用 async/await。请参阅: 异步教程
快照
it('works', () => {
const output = something()
expect(output).toMatchSnapshot()
})
首次运行时会创建快照。后续运行会与已保存的快照进行比对。请参阅: 快照测试
React 测试渲染器
import renderer from 'react-test-renderer'
it('works', () => {
const tree = renderer.create(
<Link page="https://www.facebook.com">Facebook</Link>
).toJSON()
expect(tree).toMatchSnapshot()
})
React 的测试渲染器可用于 Jest 快照。参见: 快照测试
定时器
jest.useFakeTimers()
it('works', () => {
jest.runOnlyPendingTimers()
jest.runTimersToTime(1000)
jest.runAllTimers()
})
模拟函数 (Mock functions)
模拟函数 (Mock functions)
const fn = jest.fn()
const fn = jest.fn(n => n * n)
断言
expect(fn)
.toHaveBeenCalled()
.toHaveBeenCalledTimes(number)
.toHaveBeenCalledWith(arg1, arg2, ...)
.toHaveBeenLastCalledWith(arg1, arg2, ...)
expect(fn)
.toHaveBeenCalledWith(expect.anything())
.toHaveBeenCalledWith(expect.any(constructor))
.toHaveBeenCalledWith(expect.arrayContaining([ values ]))
.toHaveBeenCalledWith(expect.objectContaining({ props }))
.toHaveBeenCalledWith(expect.stringContaining(string))
.toHaveBeenCalledWith(expect.stringMatching(regexp))
实例
const Fn = jest.fn()
a = new Fn()
b = new Fn()
Fn.mock.instances
// → [a, b]
参见: .mock 属性
调用
const fn = jest.fn()
fn(123)
fn(456)
fn.mock.calls.length // → 2
fn.mock.calls[0][0] // → 123
fn.mock.calls[1][0] // → 456
参见: .mock 属性
返回值
const fn = jest.fn(() => 'hello')
或者:
jest.fn().mockReturnValue('hello')
jest.fn().mockReturnValueOnce('hello')
模拟实现 (Mock implementations)
const fn = jest.fn()
.mockImplementationOnce(() => 1)
.mockImplementationOnce(() => 2)
fn() // → 1
fn() // → 2