1

我正在写一些 expect.js 匹配器,我想自己测试匹配器。所以我想写正面和负面的测试。假设我写过

toContainItem(name);

像这样使用;

expect(femaleNames).toContainItem('Brad'); // test fails
expect(femaleNames).toContainItem('Angelina'); // test passes

我想做的是为否定情况编写一个测试,就像这样;

 it('should fail if the item is not in the list', function() {
     expect(function() {
         expect(femaleNames).toContainItem('Brad'); 
     }).toFailTest('Could not find "Brad" in the array');
 });

我不确定如何在不使包含测试失败的环境中运行失败的测试代码。这可能吗?


编辑:根据 Carl Manaster 的回答,我想出了一个期望的扩展,允许上面的代码工作;

expect.extend({
    toFailTest(msg) {
        let failed = false;
        let actualMessage = "";
        try
        {
            this.actual();
        } 
        catch(ex)
        {
            actualMessage = ex.message;
            failed = true;
        }

        expect.assert(failed, 'function should have failed exception');

        if(msg) {
            expect.assert(actualMessage === msg, `failed test: expected "${msg}" but was "${actualMessage}"`);
        }
    }
});
4

1 回答 1

1

我认为您可以将内部期望包装在 try/catch 块中,在其中清除 catch 子句中的失败变量,然后对变量的值进行实际断言。

let failed = true;
try {
  expect(femaleNames).toContainItem('Brad');
} catch (e) {
  failed = false;
}
expected(failed).toBe(false);
于 2017-01-01T20:02:25.150 回答