Jest 进阶用法
Jest API
测试文件中,Jest 将所有的方法和对象放入到全局环境中,不需要导入任何内容就可以使用。不过也支持显式导入。
pnpm i @jest/globals -D
js
import { describe, expect, test } from '@jest/globals';
js
Test 函数
test 函数别名:it(name, fn, timeout)
,test 函数就是一个测试用例。
test(name, fn, timeout)
test.concurrent(name, fn, timeout)
test.concurrent.each(table)(name, fn, timeout)
test.concurrent.only.each(table)(name, fn)
test.each(table)(name, fn, timeout)
test.only(name, fn, timeout)
:仅运行当前测试用例(针对当前模块)
Expect 匹配器
编写测试前,通常需要检查值是否满足某些条件。Expect 支持访问许多 “匹配器”,以验证不同的内容。
test('global expect', () => {
expect(2 + 2).toBe(4); // 匹配数字
expect({ name: 'jack' }).toEqual({ name: 'jack' }); // 匹配对象
expect('yueluosensen').toMatch(/yueluo/); // 正则匹配
expect(4).toBeGreaterThan(2); // 大于
expect(4).toBeLessThan(5); // 小于
})
js
更多用法:https://jestjs.io/docs/expect
describe 函数
describe 创建一个将几个测试组合在一起的块。
describe('demo', () => {
test('sum(1, 2) result is 3', () => {
expect(sum(1, 2)).toBe(3);
})
test('subtract(2, 1) result is 1', () => {
expect(subtract(2, 1)).toBe(1);
})
})
describe('global', () => {
test('global expect', () => {
expect(2 + 2).toBe(4); // 匹配数字
expect({ name: 'jack' }).toEqual({ name: 'jack' }); // 匹配对象
expect('yueluosensen').toMatch(/yueluo/); // 正则匹配
expect(4).toBeGreaterThan(2); // 大于
expect(4).toBeLessThan(5); // 小于
})
})
js
如果测试用例同时写在一个文件中,可以将相关的测试用例进行分组。
相关用法:
describe(name, fn)
describe.each(table)(name, fn, timeout)
describe.only(name, fn)
describe.only.each(table)(name, fn)
describe.skip(name, fn)
describe.skip.each(table)(name, fn)
生命周期钩子
beforeAll(fn, timeout)
:测试用例之前执行(仅运行一次)beforeEach(fn, timeout)
:每个测试用例运行之前,都会执行一次afterAll(fn, timeout)
:测试用例执行完毕执行(仅运行一次)afterEach(fn, timeout)
:每个测试用例执行完毕之后,都会执行一次
Jest 对象
Jest 对象自动位于每个测试文件中的范围内。
jest 对象中的方法有助于创建模拟,可以控制 Jest 的整体行为。也可以手动导入。
// jest.autoMockOn
// jest.useFakeTimers
js
详情内容参考:https://jestjs.io/docs/jest-object。
常用匹配器
https://jestjs.io/docs/using-matchers。
Common Matchers
describe('common matchers', () => {
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
expect('hello').toBe('hello');
expect(true).toBe(true);
const author = { name: 'yueluo' };
expect(author).toBe(author); // toBe 只可以判断对象引用
expect({ name: 'yueluo' }).toEqual({ name: 'yueluo' }); // toEqual 可以判断对象属性是否相同
});
});
js
Truthiness
describe('truthiness', () => {
test('null', () => {
const n = null;
expect(n).toBeNull(); // 判断为 null
expect(n).toBeDefined(); // 判断是否已定义
expect(n).not.toBeUndefined(); // 判断不是未定义
expect(n).not.toBeTruthy(); // 判断不是 true
expect(n).toBeFalsy(); // 判断是 false
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull(); // 判断不是 null
expect(z).toBeDefined(); // 判断是否已定义
expect(z).not.toBeUndefined(); // 判断不是未定义
expect(z).not.toBeTruthy();// 判断不是 true
expect(z).toBeFalsy(); // 判断是 false
});
});
js
Numbers
describe('numbers', () => {
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
})
test('adding floating point numbers', () => {
const value = 0.1 + 0.2;
//expect(value).toBe(0.3); This won't work because of rounding error
expect(value).toBeCloseTo(0.3); // This works.
});
})
js
Strings
describe('strings', () => {
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
})
js
Array and iterables
describe('arrays', () => {
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];
test('the shopping list has milk on it', () => {
expect(shoppingList).toContain('milk');
expect(shoppingList.length).toBe(5);
expect(new Set(shoppingList)).toContain('milk');
});
})
js
Exceptions
describe('exceptions', () => {
function compileAndroidCode() {
throw new Error('you are using the wrong JDK');
}
test('compiling android goes as expected', () => {
expect(() => compileAndroidCode()).toThrow();
expect(() => compileAndroidCode()).toThrow(Error);
// You can also use the exact error message or a regexp
expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);
});
})
js
And More
This is just a taste. For a complete list of matchers, check out the reference docs.
Once you’ve learned about the matchers that are available, a good next step is to check out how Jest lets you test asynchronous code.
测试异步代码
新建 async.test.js 文件,并执行以下命令。
npx jest async.test.js --watch
js
回调函数形式
function getData (callback) {
setTimeout(() => {
callback({ author: 'heora' })
}, 1000)
}
// 错误示范:这种写法不会等待定时器结束
test('async fail', () => {
getData(data => {
expect(data).toEqual({ author: 'heora' })
})
})
// 正确做法
test('async success', (done) => {
getData(data => {
done();
expect(data).toEqual({ author: 'heora' })
})
})
js
Promise 形式
function getData () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ author: 'heora' })
}, 1000)
})
}
test('async promise1', (done) => {
getData().then(data => {
done();
expect(data).toEqual({ author: 'heora' })
})
})
test('async promise2', () => {
return getData().then(data => {
expect(data).toEqual({ author: 'heora' })
})
})
test('async promise3', () => {
// return expect(getData()).rejects.toMatch('error');
return expect(getData()).resolves.toEqual({ author: 'heora' });
})
test('async promise4', async () => {
try {
const data = await getData();
expect(data).toEqual({ author: 'heora' })
} catch (error) {
expect(error).toMatch('error');
}
})
test('async promise5', async () => {
// await expect(getData()).rejects.toMatch('error');
await expect(getData()).resolves.toEqual({ author: 'heora' });
})
js
Mock
定时器
长时间处理
// 针对超长时间的异步函数
describe('timer: long', () => {
function getData () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ author: 'heora' })
}, 10 * 1000)
})
}
// mock 定时器
jest.useFakeTimers();
test('timer mock', () => {
// 至少存在一次断言调用
expect.assertions(1);
getData().then(data => {
expect(data).toEqual({ author: 'heora' })
})
// 快进所有定时器到结束
jest.runAllTimers()
})
});
js
循环处理
describe('timer: loop', () => {
function getData () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ author: 'heora' })
getData();
}, 10 * 1000)
})
}
// mock 定时器
jest.useFakeTimers();
test('timer mock', () => {
// 至少存在一次断言调用
expect.assertions(1);
getData().then(data => {
expect(data).toEqual({ author: 'heora' })
})
// 快进当前进行的定时器结束,不等待其它
jest.runOnlyPendingTimers()
})
});
js
快进指定时间
describe('timer: set time', () => {
function getData () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ author: 'heora' })
}, 10 * 1000)
})
}
// mock 定时器
jest.useFakeTimers();
test('timer mock', () => {
// 至少存在一次断言调用
expect.assertions(1);
getData().then(data => {
expect(data).toEqual({ author: 'heora' })
})
jest.advanceTimersByTime(9 * 1000);
jest.advanceTimersByTime(1 * 1000);
})
});
js
函数
基本用法
function forEach (items, callback) {
for (let index = 0; index < items.length; index++) {
callback(items[index], index);
}
}
test('mock functions', () => {
const items = ['js', 'ts', 'nodejs'];
const mockFn = jest.fn((value, index) => {
return value + 1;
});
// 调用函数设置返回值会覆盖上面的实现
// mockFn.mockReturnValue(123);
// 调用函数设置第一个返回值
mockFn.mockReturnValueOnce(123);
forEach(items, mockFn);
console.log(mockFn.mock);
expect(mockFn.mock.calls.length).toBe(items.length);
expect(mockFn.mock.calls[0][0]).toBe('js');
expect(mockFn.mock.calls[0][1]).toBe(0);
})
js
模拟模块
例如使用 axios,不需要真实请求,可以提高测试速度。
// users.json
[
{
"author": "yueluo"
},
{
"author": "heora"
}
]
js
// user.js
import axios from "axios";
export const getAllUsers = () => {
return axios.get('/users.json').then(res => res.data);
}
js
// user.test.js
import axios from 'axios';
import { getAllUsers } from './user';
import users from './users.json';
jest.mock('axios');
test('fetch users', async () => {
const resp = { data: users };
axios.get.mockResolvedValue(resp);
const data = await getAllUsers();
expect(data).toEqual(users);
})
js
模拟实现
当函数内部存在大量计算,或者功能较多时,可以使用。
// foo.js
export default function () {
console.log('foo');
}
js
// foo.test.js
jest.mock('./foo');
import foo from "./foo";
foo.mockImplementation(() => 42);
test('mock implementations', () => {
expect(foo()).toBe(42);
});
js
模拟名称
const myMockFn = jest
.fn()
.mockReturnValue('default')
.mockImplementation(scalar => 42 + scalar)
.mockName('add42');
js
自定义匹配器
// The mock function was called at least once
expect(mockFunc).toHaveBeenCalled();
// The mock function was called at least once with the specified args
expect(mockFunc).toHaveBeenCalledWith(arg1, arg2);
// The last call to the mock function was called with the specified args
expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2);
// All calls and the name of the mock is written as a snapshot
expect(mockFunc).toMatchSnapshot();
js
更多用法可以点击这里查看。
钩子函数
可以在测试用例执行前后做一些通用的操作。
const data = {
author: 'yueluo'
}
let user = null;
beforeAll(() => {
console.log('before all')
})
afterAll(() => {
console.log('after all')
})
// 每个实例运行之前
beforeEach(() => {
user = Object.assign({}, data)
})
// 每个实例运行之后
afterEach(() => {
user = null
})
test('test 1', () => {
user.author = 'heora';
expect(user.author).toBe('heora')
})
test('test 2', () => {
expect(user.author).toBe('yueluo')
})
js
分组
describe 内部的 beforeEach 仅对当前内部的测试用例生效
describe('group', () => {
beforeEach(() => {
console.log('group before each')
})
afterEach(() => {
console.log('group after each')
})
test('test1', () => {
console.log('group test1')
})
test('test2', () => {
console.log('group test2')
})
})
js
DOM 测试
Jest 配合 jest-environment-jsdom
可以做到在 nodejs 环境中模拟 DOM API。
jsdom 不再默认内置于 jest v28 ,需要显式安装
pnpm i jest-environment-jsdom -D
js
/**
* @jest-environment jsdom
*/
function renderHtml () {
const div = document.createElement('div');
div.innerHTML = `
<h1>Hello World</h1>
`
document.body.appendChild(div);
}
test('dom testing', () => {
renderHtml();
expect(document.querySelector('h1').innerHTML).toBe('Hello World');
})
js
Vue 组件测试
pnpm i vue@2
js
/**
* @jest-environment jsdom
*/
import Vue from 'vue/dist/vue';
function renderVueComponent () {
document.body.innerHTML = `
<div id="app"></div>
`
new Vue({
template: `
<div id="app">
<h1>{{ message }}</h1>
</div>
`,
data: {
message: 'Hello World'
}
}).$mount('#app');
}
test('vue testing', () => {
renderVueComponent();
console.log(document.body.innerHTML)
expect(document.body.innerHTML).toMatch(/Hello World/)
})
js
快照测试
/**
* @jest-environment jsdom
*/
import Vue from 'vue/dist/vue';
function renderVueComponent () {
document.body.innerHTML = `
<div id="app"></div>
`
new Vue({
template: `
<div id="app">
<h1>{{ message }}</h1>
</div>
`,
data: {
message: 'Hello World'
}
}).$mount('#app');
}
test.only('Snapshot Testing', () => {
renderVueComponent();
// 首次运行时,会生成快照文件
// 下次运行测试会与快照文件进行比对,如果不一致测试失败
expect(document.body.innerHTML).toMatchSnapshot();
})
js
快照文件(__snapshots__/vue.test.js.snap
):
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Snapshot Testing 1`] = `
"
<div id=\\"app\\"><h1>Hello World</h1></div>
"
`;
js
如果模板确实有更改,我们可以更新快照。
npx jest vue.test.js --updateSnapshot
js
总结
我们已经学习完 Jest 所有内容,希望你可以在工作中更好地去使用它。