2017-01-01 65 views
1

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

我不知道如何在一个环境中,它不会失败的含试运行失败我测试代码。这可能吗?


编辑:基于卡尔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

我想你可以包装内期望在一个try/catch块,在那里你的catch子句中清除故障变量,然后做出关于变量的值,您的实际断言。

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

感谢卡尔 - 会放弃它!不知道它通过例外工作。 –

+1

卡尔 - 谢谢你。这是我提出的解决方案的核心,现在编辑回我的问题。我所做的所有事情都是把它包装起来,这样你就可以编写'expect(fn).toFailTest(expectedErrorMessage)' –