相关文章
1. expect 的用法及 ”匹配器“
- expect 用来检查某个值是否符合预期,匹配器则是匹配的方法。
- expect.not 用来检查某个值是否不匹配结果
- expect.resolves 用来结构 promise ,从而判断其返回值(注意:这种 expect 需要在 test 中 return expect; 或者使用 async await )
- expect.rejects 同上用来判断 promise reject 后的结果
- expect.assertions(number) 用来验证在测试期间调用了一定数量的断言,通常用在测试异步代码中
常用匹配器
test('Test Matcher ', async () => {
await expect(Promise.resolve('some result'))
.resolves.toBe('some result');
expect(2 + 2).not.toBe(5);
expect(2 + 2).toBe(4);
expect(2.1 + 2.2).toBeCloseTo(4.3);
expect(20).toBeGreaterThan(10);
expect(20).toBeLessThan(30);
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(null).toBeDefined();
expect([]).toBeTruthy();
expect('').toBeFalsy();
expect('xxxsss').toMatch(/^[a-z]+$/i);
expect([{a: 1}]).toEqual([{a: 1}]);
expect(['AAA', 'BBB']).toContain('AAA');
expect(() => {
throw new Error('test error')
}).toThrow('test error');
});
test('Test Async Code -- Callback', (done) => {
function callback(data: string) {
try {
expect(data).toBe('peanut butter');
done();
} catch (error) {
done(error);
}
}
fetchData(callback);
})
test('Test Async Code -- Async', async () => {
await expect(fetchData()).resolves.toBe('peanut butter');
await expect(fetchData()).rejects.toMatch('error');
});
test('Test Async Code -- Promise', async () => {
expect.assertions(1);
return fetchData().catch(e => expect(e).toMatch('error'));
});
更多 expect 及 匹配器使用查看
2. Mock 函数
jest 提供了 mock 函数,可以用来帮助捕获函数的调用以及在调用过程中的传参, 允许测试时配置返回值,可以用来做假数据
import axios from 'axios';
import Utils from './utils';
jest.mock('axios');
const axiosReq = axios as jest.Mocked<typeof axios>;
const utils = new Utils();
describe('测试 Mock 函数', () => {
test('捕获函数调用', async () => {
utils.init(5, 1000);
const mockFn = jest.fn((num: number) => num * 10);
utils.useCallbackFn(mockFn as unknown as (() => any));
expect(mockFn.mock.calls.length).toBe(2);
expect(mockFn.mock.calls[0][0]).toBe(5);
expect(mockFn.mock.results[0].value).toBe(50);
const MockClass = jest.fn();
const a = new MockClass();
expect(MockClass.mock.instances[0]).toBe(a);
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveNthReturnedWith(1, 50);
const mockFn2 = jest.fn();
mockFn2.mockReturnValue(90);
expect(mockFn2()).toBe(90);
axiosReq.get.mockResolvedValue({data: [90, 200]});
await expect(utils.getData()).resolves.toEqual({data: [90, 200]})
})
})
查看 其他 mock 函数相关 API
3. jest 配置文件
配置文件
- 执行 jest --init ,回答几个问题后就会生成 jest.config.(js|ts) 配置文件
- 除此之外也可以将配置加载 package.json 的 jest 字段上
- jest.config.(js|ts) 文件中可以 export 一个配置对象,或者是一个 async function
export default {
bail: 1,
collectCoverage: true,
coverageDirectory: "coverage",
collectCoverageFrom: ['src/components/**', '!**/node_modules/**', '!src/**/*.d.ts'],
roots: [
"<rootDir>/src/components"
],
testMatch: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
setupFiles: ['react-app-polyfill/jsdom'],
setupFilesAfterEnv: ['<rootDir>/tests/setupTests.ts'],
testEnvironment: "jsdom",
moduleNameMapper: {
'^tests/(.*)$': '<rootDir>/tests/$1',
"\\.(css|less)$": "identity-obj-proxy"
},
"transform": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
}
}
更多配置查看 或者查看
参考:
|