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([]); });