分配失败消息以期待呼叫

时间:2014-05-20 14:30:09

标签: angularjs mocha chai

我目前正在学习AngularJS,其中一部分涉及创建测试。目前我正在尝试研究如何为失败的测试创建更有用的错误消息。例如,如果我在Java-land并编写JUnit测试,我会做类似于此的事情:

assertTrue( "The foo value should be true at this point", bar.isFoo() );

这样,如果检查失败,我将在日志中获得第一个参数。

对于mocha中的布尔检查(使用chai和sinon,如果有所不同)我有......

expect(broadcastSpy.calledWith('order.add')).to.be.true;

如果失败,我会得到以下内容:

expected false to be true
AssertionError: expected false to be true

有没有办法在测试我的应用时复制有用的失败消息?

2 个答案:

答案 0 :(得分:10)

我在answer中提到了一个与此不同的问题。我刚检查了Chai的代码,以确保自从我写完答案后没有任何改变,发现以下情况仍然存在。代码:

expect(foo).to.be.true;

不接受自定义消息,因为true是通过getter获取其值的属性。但是,你可以这样做:

expect(foo).to.equal(true, "foo should be true");

如果断言失败,则获取自定义消息。

Chai的断言接口支持所有断言的消息,例如:

assert.isTrue(foo, "foo should be true");

答案 1 :(得分:0)

我偶然发现了一个也许是更令人满意的答案:expect(foo, 'foo should be true').to.be.true; 可以将消息作为第二个参数,例如:

foo

这将呈现以下输出(在falseAssertionError: foo should be true: expected false to be true 的情况下):

expect

来源:请参见Chai documentation-搜索文本“消息也可以作为{{1}}的第二个参数给出。”