5

I'm currently learning AngularJS and part of that covers creating tests. At the moment I'm trying to work out how to create more useful error messages for failing tests. For example, if I was in Java-land and writing JUnit tests I would do something akin to this:

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

That way, I'll get that first parameter in the log if the check fails.

For boolean checks in mocha (with chai and sinon, in case that makes a difference) I have...

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

If that fails then I get the following:

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

Is there a way to replicate that helpful failure message while testing my app?

chooban
  • 9,018
  • 2
  • 20
  • 36
  • 1
    DRY js tests aren't very useful. Be explicit. `it('bar.isFoo() should be true when stuff happens', function() { expect(broadcastSpy.calledWith('order.add')).to.be.true; });` – J.Wells May 20 '14 at 14:38
  • Perhaps I'm simply not writing the tests in a very idiomatic way, as I have multiple calls to expect. – chooban May 20 '14 at 14:47
  • I would agree. A test should be a test. A group of tests are a suite. If a successful test requires multiple assertions, it should still have a concise success/fail criteria. – J.Wells May 20 '14 at 14:52

2 Answers2

11

I mentioned something about this in an answer to a different question. I've just checked Chai's code to be sure that nothing has changed since I wrote that answer and found the following is still true. The code:

expect(foo).to.be.true;

does not accept a custom message because true is a property that obtains its value through a getter. You can, however, do this:

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

to get a custom message if the assertion fails.

Chai's assert interface supports messages on all assertions, for instance:

assert.isTrue(foo, "foo should be true");
Community
  • 1
  • 1
Louis
  • 146,715
  • 28
  • 274
  • 320
  • Thanks! I suspect my tests will become a bit of a mix of styles until I decide on what I believe to be the One True Way! :) – chooban May 20 '14 at 14:56
0

I just happened to stumble upon what perhaps is a more satisfactory answer: expect can take a message as a second argument, like such:

expect(foo, 'foo should be true').to.be.true;

This renders the following output (in case foo is false):

AssertionError: foo should be true: expected false to be true

Source: see the Chai documentation - search for the text "The message can also be given as the second argument to expect."

Erwin Wessels
  • 2,972
  • 1
  • 24
  • 17