我正在写一些 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}"`);
}
}
});