Using Matchers

    最简单的测试值的方法是看是否精确匹配。

    在此代码中,expect (2 + 2) 返回一个”期望”的对象。 你通常不会对这些期望对象调用过多的匹配器。 在此代码中,.toBe(4) 是匹配器。 当 Jest 运行时,它会跟踪所有失败的匹配器,以便它可以为你打印出很好的错误消息。

    toBe 使用 Object.is 来测试精确相等。 如果您想要检查对象的值,请使用 toEqual 代替:

    1. test('object assignment', () => {
    2. const data = {one: 1};
    3. data['two'] = 2;
    4. expect(data).toEqual({one: 1, two: 2});
    5. });

    toEqual 递归检查对象或数组的每个字段。

    1. test('adding positive numbers is not zero', () => {
    2. for (let a = 1; a < 10; a++) {
    3. for (let b = 1; b < 10; b++) {
    4. expect(a + b).not.toBe(0);
    5. }
    6. }
    7. });

    Truthiness

    在测试中,你有时需要区分 undefinednull,和 false,但有时你又不需要区分。 Jest 让你明确你想要什么。

    • toBeNull 只匹配 null
    • toBeDefinedtoBeUndefined 相反
    • toBeTruthy 匹配任何 if 语句为真
    • toBeFalsy 匹配任何 if 语句为假

    例如:

    您应该使用匹配器最精确地对应您的代码你想要什么。

    大多数的比较数字有等价的匹配器。

    1. test('two plus two', () => {
    2. const value = 2 + 2;
    3. expect(value).toBeGreaterThan(3);
    4. expect(value).toBeGreaterThanOrEqual(3.5);
    5. expect(value).toBeLessThan(5);
    6. expect(value).toBeLessThanOrEqual(4.5);
    7. // toBe and toEqual are equivalent for numbers
    8. expect(value).toBe(4);
    9. expect(value).toEqual(4);
    10. });
    1. test('两个浮点数字相加', () => {
    2. const value = 0.1 + 0.2;
    3. //expect(value).toBe(0.3); 这句会报错,因为浮点数有舍入误差
    4. expect(value).toBeCloseTo(0.3); // 这句可以运行
    5. });

    字符串

    您可以检查对具有 正则表达式的字符串︰

    你可以通过 toContain来检查一个数组或可迭代对象是否包含某个特定项:

    1. const shoppingList = [
    2. 'kleenex',
    3. 'trash bags',
    4. 'paper towels',
    5. 'beer',
    6. ];
    7. test('the shopping list has beer on it', () => {
    8. expect(shoppingList).toContain('beer');
    9. expect(new Set(shoppingList)).toContain('beer');
    10. });

    例外

    如果你想要测试的特定函数抛出一个错误,在它调用时,使用 toThrow

    1. function compileAndroidCode() {
    2. throw new Error('you are using the wrong JDK');
    3. }
    4. test('compiling android goes as expected', () => {
    5. expect(compileAndroidCode).toThrow();
    6. expect(compileAndroidCode).toThrow(Error);
    7. // You can also use the exact error message or a regexp
    8. expect(compileAndroidCode).toThrow('you are using the wrong JDK');
    9. });

    这些只是浅尝辄止。 这些只是一部分,有关匹配器的完整列表,请查阅 。