匹配器的使用
Jest使用“匹配器”的机制让你可以使用各种方法进行测试 这篇文档将向你介绍一些常用的匹配器, For the full list, see the expect API doc.
常用的匹配器
最简单测试一个值的方法是使用精确匹配的方法。
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
In this code, expect(2 + 2) returns an "expectation" object. 你通常不会对这些期望对象调用过多的匹配器。 In this code, .toBe(4) is the matcher. 当 Jest 运行时,它会跟踪所有失败的匹配器,以便它可以为你打印出很好的错误消息。
toBe uses Object.is to test exact equality. If you want to check the value of an object, use toEqual:
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
toEqual recursively checks every field of an object or array.