测试expect.js的扩展

时间:2017-01-01 13:55:02

标签: tdd mocha 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}"`);
        }
    }
});

1 个答案:

答案 0 :(得分:1)

我认为你可以在try / catch块中包含内部expect,你可以在catch子句中清除失败变量,然后对变量的值进行实际断言。

let failed = true;
try {
  expect(femaleNames).toContainItem('Brad');
} catch (e) {
  failed = false;
}
expected(failed).toBe(false);