1. 匹配器 Matchers
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
test()
别名 it()
expect(...).not.toBe(...)
测试相反的匹配
普通匹配器
-
toBe
使用的是Object.is()
判断两个值是否相等, 如果判断object的话要使用toEqual
代替。 -
toEqual
递归检查对象或数组的每个字段。 -
toBeNull
只匹配null
-
toBeUndefined
只匹配undefined
-
toBeDefined
与toBeUndefined
相反 -
toBeTruthy
匹配任何if
语句为真 -
toBeFalsy
匹配任何if
语句为假
数字:
toBeGreaterThan
大于toBeGreaterThanOrEqual
大于等于toBeLessThan
小于toBeLessThanOrEqual
小于等于toBeCloseTo
比较浮点数相等,忽略舍入误差
字符串:
toMatch
使用正则表达式匹配字符串toContain
检查数组或可迭代对象是否包含某个特定选项
test('there is no I in team', () => {
expect('team').not.toMatch(/I/)
})
测试异常toThrow
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/);
})
完整的匹配器列表, 请查阅 参考文档
2. 测试异步代码
1. done
参数 回调
使用单个参数 done
函数,Jest会等 done()
回调函数执行结束后结束测试。如果done
永远不会调用,这个测试将失败。
test('the data is peanut butter', done => {
function callback (data) {
expect(data).toBe('peanut butter');
done();
}
// fetchData 是待测试的异步函数
fetchData(callback);
})
2. Promise
test 返回一个Promise
, Jest 会等到Promise
完成调用resolve
方法后结束,如果rejected
, 测试自动失败。
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
})
})
一定不要忘记把 promise
作为返回值。如果你忘了 return
语句的话,在 fetchData
返回的这个 promise
被 resolve
、then()
有机会执行之前,测试就已经被视为已经完成了。
3. Async/Await
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
})
test('the fetch fails with an error', async () => {
expect.assertions(1);
try {
await fetchData();
} catch (e) {
expect(e).toMatch('error');
}
});
3. setup and teardown
Jest提供辅助函数beforeEach
, beforeAfter
, beforeAll
, beforeAfter
处理运行测试前、后的一些工作。
默认情况下,before
和after
中的块可以应用到文件中的每一个测试。此外,可以使用describe
块将测试分组。describe
块内的before
和after
只适用于该describe
块内部。文件顶部的before
after
先执行,describe
块内的before
after
后执行。
// 一次性设置,只需要在文件的开头做一次设置。
beforeAll(() => {
initDatabase();
})
afterAll(() => {
clearDatabase();
})
beforeEach(() => {
initData(); // 每个测试之前调用
})
afterEach(() => {
clearData(); // 每个测试后调用
})
test('do test1', () => {
expect(...).toBe(...)
})
test('do test2', () => {
expect(...).toBe(...)
})
describe('some tests', () => {
beforeEach(() => {
initSomeData();
})
test('test in describe', () => {
...
})
})
4. test.only
但测试失败时,第一件要检查的事就是,当仅运行这一条测试时,是否仍然失败。方法就是把test
改成test.only
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
5. mock函数
jest.fn
.mock
属性
所有的mock函数都有一个特殊的 .mock
属性,它保存了关于此函数如何被调用、调用时的返回值信息。
.mock
属性还追踪每次调用时this
的值.mock.instances
。
const mockFn = jest.fn()
mockFn.mock.calls.length
mock方法调用的次数
mockFn.mock.calls[i][j]
第i次调用时的第j个参数
mockFn.mock.results[i]
第i次调用时的返回值
mockFn.mock.instances[i]
第i次调用时的this
值
mock 返回值
mock方法也可以用来在测试代码中注入测试值。
mockFn.mockReturnValueOnce()
mockFn.mockReturnVaule()
const filterTestFn = jest.fn();
// Make the mock return `true` for the first call,
// and `false` for the second call
filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false);
const result = [11, 12].filter(filterTestFn);
console.log(result);
// > [11]
console.log(filterTestFn.mock.calls);
mock Promise返回值
jest.mock(...)
mockResolveValue
import axios from 'axios';
class Users {
static all(){
return axios.get('/user.json').then(resp => resp.data)
}
}
export default Users;
测试代码如下:
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
const users = [{name: 'Blob'}]
const resp = {data: users};
axios.get.mockResolvedValue(resp);
return Users.all().then(data => expect(data).toEqual(users));
})
mock 方法的实现
mockImplementation
mockImplementationOnce
mockReturnThis
链式方法
const myObj = {
myMethod: jest.fn().mockReturnThis(),
};
// is the same as
const otherObj = {
myMethod: jest.fn(function() {
return this;
}),
};
6. Snapshot Testing 快照测试
快照测试是测试你的渲染组件的图片,并将其与组件的以前的图片进行比较。