测试 expect.js 的扩展
Testing an extension to expect.js
我正在编写一些 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}"`);
}
}
});
我认为你可以将内部 expect 包装在一个 try/catch 块中,在其中清除 catch 子句中的失败变量,然后对该变量的值进行实际断言。
let failed = true;
try {
expect(femaleNames).toContainItem('Brad');
} catch (e) {
failed = false;
}
expected(failed).toBe(false);
我正在编写一些 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}"`);
}
}
});
我认为你可以将内部 expect 包装在一个 try/catch 块中,在其中清除 catch 子句中的失败变量,然后对该变量的值进行实际断言。
let failed = true;
try {
expect(femaleNames).toContainItem('Brad');
} catch (e) {
failed = false;
}
expected(failed).toBe(false);