Jest is a delightful JavaScript Testing Framework with a focus on simplicity.
It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!
三体
$ mkdir jestTest && cd ./jestTest $ npm init -y
# 初始化 jest 配置 $ npx jest --init # 安装 $ npm install -D jest
babel
$ npm install -D @babel/core @babel/preset-env $ touch babel.config.js
babel.config.js 内容java
module.exports = { presets: [ ["@babel/preset-env", { targets: { node: 'current' } }], ] }
$ mkdir src && cd ./src $ touch index.js index.test.js
expect(1 + 2).toBe(3); // 精确匹配 expect({one: 1}).toEqual({ one: 1 }); // 深度匹配 expect(null).toBeNull(); // Null匹配 expect(undefined).toBeUndefined(); // undefined 匹配 expect(var).toBeDefined(); // var是否认义 expect(true).toBeTruthy(); // true 匹配 expect(false).toBeFalsy(); // false 匹配 expect(false).not.toBe(true); // 取反匹配 expect(1).toBeGreaterThan(0); // 大于 expect(1).toBeLessThan(2); // 小于 expect(1).toBeGreaterThanOrEqual(1); // 大于等于 expect(1).toBeLessThanOrEqual(1); // 小于等于 expect(0.1 + 0.2).toBeCloseTo(0.3); // 浮点数 expect('toMatch').toMatch(/to/) // 是否包含 expect([1, 2, 3]).toContain(1) // 是否包含某些元素 expect(() => { throw new Error() }).toThrow(); // 异常匹配
备用函数
function loadData(){ return new Promise((resolve, reject)=>{ resolve({ code: 200, data: {} }); }) }
// 经过返回 test('should loadData', async () => { // expect.assertions(1); // 必须执行一个expect return loadData().then(res => { expect(res.code).toBe(200) }); }); // 经过调用参数 test('should loadData', (deno) => { loadData().then(res => { expect(res.code).toBe(200) deno(); }); }); // 经过resolves test('should loadData', (deno) => { return expect(loadData()).resolves.toMatchObject({ code: 200 }); });
// 开始执行一次 beforeAll(() => { console.log('befaoreAll'); }); // 每一个测试用例都会执行 beforeEach(() => { console.log('beforeEach'); }); // 每一个测试用例执行后都会执行 afterEach(() => { console.log('afterEach'); }); // 勾子执行完毕 afterAll(() => { console.log('afterAll'); }); describe('describe', () => {}); test('should xxx', () => {});
const func = jest.fn(()=>{}); func.mockReturnValueOnce('value1') .mockReturnValueOnce('value2'); func.mockReturnValue('value'); console.log(func.mock); // mock 返回数据
import ajax from './utils/ajax/ajax' jest.mock('./utils/ajax/ajax'); test('should mock', async () => { ajax.get.mockResolvedValue({ data: { data: [], code: 200 } }); // 模拟数据 const data = await loadTestData(); expect(data.data).toEqual([]); });