Jest 常用Api

1,157 阅读4分钟

Globals Api

Api主要用途其它
describe一个describe为一组,不推荐describe嵌套describe(name, fn)
test(it)一个describe可以有多个it,最常用的组合方式test(name, fn, timeout)
afterAll清理一些跨测试共享的全局设置状态在所有test执行完毕后执行一次
afterEach清理每个测试创建的一些临时状态在每一个test执行完后都会执行
beforeAll设置一些测试使用的全局状态在所有test执行之前执行一次
beforeEach重置一些被测试使用的全局状态在每一个test执行前都会执行
test.each优化重复使用不同的数据,但结构相同的测试同describe.each用法一样
describe.each优化重复使用不同的数据,但结构相同的测试接受一个二维数组或者数组对象(例子
describe.only只运行一个describe一般不用,出于某些特殊原因,只运行主要describe
describe.only.eachonly和each的结合
describe.skip跳过当前test通常是临时注释掉一大块测试的更干净的替代方法
describe.skip.eachskip和each的结合
test.concurrent多个concurrent测试同时运行
test.concurrent.only.eachconcurrent和only和each的结合
test.only出于某些特殊原因,只运行主要test只运行一个test
test.only.eachonly和each的结合
test.skip跳过当前test
test.skip.eachskip和each的结合
test.todo加回调会报错,只给一个参数,用于编写测试计划

Expect Api

Api主要用途其它
expect测试值时都会使用该函数expect与匹配器 组合起来断言
expect.extend扩展自定义匹配器支持快照支持异步
expect.anything匹配除null或undefined之外的任何内容null或undefined会报错
expect.any通过类型去断言类型错误将报错
expect.arrayContaining支持匹配数组中的部分元素被断言的数组参数可以多不可以少
expect.stringContaining支持匹配字符串中的部分字符被断言的字符可以多不可以少
expect.assertions验证在测试期间调用了一定数量的断言是异步的
expect.hasAssertions验证在测试期间至少调用了一个断言是异步的
expect.objectContaining验证中对象是否包含某项属性
.toBeInstanceOf断言对象是一个类的实例
.not取反
.toBe严格相等
.toEqual值相同即可
.toBeFalsy断言为假
.toBeTruthy断言为true
.toBeNull断言为null
.toBeUndefined断言为undefined
.toBeNaN断言为NaN
.toContain断言数组或字符串中是否包含严格相等
.toContainEqual断言数组或字符串中是否包含值相同即可
.toMatch断言字符串支持正则
.toThrow断言抛出错误

数字相关

Api主要用途其它
.toBeGreaterThan断言大于
.toBeGreaterThanOrEqual断言大于等于
.toBeLessThan断言小于
.toBeLessThanOrEqual断言小于等于
.toBeCloseTo断言浮点数解决0.1+0.2 !== 0.3的问题

函数相关

Api主要用途其它
.toBeCalled函数将被调用别名:toHaveBeenCalled
.toHaveBeenCalledTimes断言函数调用的次数可配合toBe等其它的匹配器
.toHaveBeenCalledWith断言函数调用的参数别名:toBeCalledWith
.toHaveBeenLastCalledWith断言指定函数指定第几次调用的参数别名:lastCalledWith
.toHaveBeenNthCalledWith断言最后一次函数调用的参数别名:nthCalledWith
.toHaveReturned断言函数有返回值别名:toReturn
.toHaveReturnedTimes断言函数返回次数别名:toReturnTimes
.toHaveReturnedWith断言函数具体的返回值别名:toReturnWith
.toHaveLastReturnedWith断言函数最后一次的返回值别名:lastReturnedWith
.toHaveNthReturnedWith断言函数指定次数的返回值别名:nthReturnedWith
.toHaveLength断言数组或者字符串的长度
.toHaveProperty断言对象中是否包含某项属性支持对象参数路径,断言指定的值
.resolves断言Promise成功回调可配合toBe等其它的匹配器
.rejects断言Promise失败的回调可配合toBe等其它的匹配器

mock 函数

mockName

指定mock函数的名字,这在报错的时候非常有用

const myMockFn = jest.fn().mockName('myMockFn');

mockFn.mock.results

指定函数返回值

fn.mock.results = [
    {
        type: 'throw',
        value: {
            /* Error instance */
        },
    },
    {
        type: 'return',
        value: 'result2',
    },
];
//期待最后一次返回结果为'result2'
expect(fn).toHaveLastReturnedWith( 'result2')

mockFn.mockClear

重置存储在mockFn.mock.calls,mockFn.mock.instancesmockFn.mock.results数组中的所有信息。

fn.mock.results = [
    {
        type: 'return',
        value: 'result2',
    },
];
fn.mockClear()
//会报错,因为清空了mock
expect(fn).toHaveLastReturnedWith( 'result2')

mockFn.mockReset

执行所有mockFn.mockClear()操作,并删除任何模拟的返回值或实现

const fn = jest.fn()

fn.mock.results = [
    {
        type: 'return',
        value: 'result2',
    },
];
fn.mockReset()
//完全重置回其初始状态时jest.fn()
expect(fn).not.toReturn()

mockFn.mockImplementation

const mockFn = jest.fn().mockImplementation(scalar => 42 + scalar);

// or: jest.fn(scalar => 42 + scalar);

const a = mockFn(0);

const b = mockFn(1);

a === 42; // true

b === 43; // true

mockFn.mock.calls[0][0] === 0; // true

mockFn.mock.calls[1][0] === 1; // true

mockFn.mockReturnValue

指定返回值

const mock = jest.fn();
mock.mockReturnValue(42);
mock()
expect(mock).toReturnWith(42)
//下面三种方式都可以达到上面的效果
//const mock = jest.fn(()=>42);

//use mockImplementation
//const mock = jest.fn().mockImplementation(()=>42);
//mock.mock.results = [{type:'return',value:42}]

mockFn.mockResolvedValue

模拟成功的回调

test('async test', async () => {
    //const asyncMock = jest.fn(()=> Promise.resolve(42));
    const asyncMock = jest.fn().mockResolvedValue(43);
    await asyncMock(); // 43
});

mockFn.mockRejectedValue

模拟失败的回调

test('async test', async () => {
    //const asyncMock = jest.fn(()=> Promise.reject(42));
    const asyncMock = jest.fn().mockRejectedValue(43);
    await asyncMock(); // 43
});

mock Modules

模拟axios

//模拟模块,可以搭配mockResolvedValue和Implementations等api使用
import axios from 'axios';
jest.mock('axios');
//模拟一个文件中部分函数
jest.mock('path', () => {
  const originalModule = jest.requireActual('path');
  return {
    __esModule: true,
    ...originalModule,
    functionName: jest.fn(() => true),
  };
});