01-使用匹配器(Using Matchers)

183 阅读2分钟

使用匹配器(Using Matchers)

  Jest使用"匹配器"使你能够用不同的方法检测值。这个文档将介绍一些常用的匹配器。请浏览expectApi文档 ,查看完整列表。

常见的匹配器

检测一个值与预期值是否完全的最简单方法。

test('two plus two is for',()=> {
    expect(2+2).toBe(4)
})

在上述代码中,expect(2 + 2) 返回一个"预期"结果。除了对这个预期结果进行匹配检测之外,你通常不想对它做其他操作。上述代码中,toBe(4) 是一个匹配检测。当 Jest 运行时,它会跟踪所有失败的匹配检测,以便于它能够输出友好的错误的信息。

toBe 使用 Object.is 检测确定值。如果你想要检测一个对象,可以使用toEqual代替:

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

toEqual 会递归数组或对象上的每个字段。

你也可以使用not对一个匹配进行取反操作。

test('adding postive number is not zero', ()=> {
    for(let a = 1; a < 10; a++) {
        for(let b = 1; b < 10; b++) {
            expect(a+b).not.toBe(0)
        }
    }
})

真值

在检测时,你有时需要区分 undefinednull以及 false,但是你有时不想对它们做区别处理。Jest 内置的匹配器让你能够明确检测期望。

  • toBeNull 只匹配 null
  • toBeUndefined 只匹配 undefined
  • toBeDefinedtoBeUndefined的结果取反
  • toBeTurthy 匹配被if语句视为true的值
  • toBeFalsely 匹配被 if语句视为 false的值

例如:

 test('null',()=> {
     const n = null;
     expect(n).toBeNull();
     expect(n).toBeDefined();
     expect(n).not.toBeUndefined();
     expect(n).not.toBeTruthy();
     expect(n).toBeFalsy();
 })
 
 test('zero',()=> {
     const z = 0;
     expect(z).not.toBeNull();
     expect(z).toBeDefined();
     expect(z).not.toBeUndefined();
     expect(z).not.toBeTruthy();
     expect(z).toBeFalsy();
 })

你应该使用能够最符合你代码预期的匹配器。

数值

比较数值的大部分方法,都有相对应的匹配器。

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)
    
    // 对 number而言,toBe 和 toBeEqual 是相同的检测
    expect(value).toBe(4)
    expect(value).toEqual(4)
})

对于浮点数而言,使用 toBeCloseTo 代替 toEqual,因为你不想一个检测的结果由一个四舍五入的错误来决定。

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.
});

字符串

你可以使用toMatch检查字符串是否符合正则表达式:

test('there is no I in team',()=> {
    expect('team').notMatch(/I/)
})

test('but there is a "stop" in Christoph', () => {
  expect('Christoph').toMatch(/stop/);
});

数组和迭代器

如何你想检查一个数组或迭代器中是否包含一个具体的值,你可以使用toContains

const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'milk',
];

test('the shopping list has milk on it', () => {
  expect(shoppingList).toContain('milk');
  expect(new Set(shoppingList)).toContain('milk');
});

异常处理

如果你想要检测一个具体的函数在被调用是,是否会抛出错误,请使用toThrow:

function compileAndroidCode() {
    throw new Error('you are using the wrong JDK')
}

test('compiling andriod goes as expected',()=> {
    expect(()=> compileAndriodCode()).toThrow();
    expect(()=> compileAndriodCode()).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/);
});

注意:抛出异常的函数需要在一个包装函数中被触发,否则 toThrow断言将会失败。