Chai.js not specifying which assertion is failing in a test
-
21-12-2019 - |
Question
I'm using mocha with chai.js for CoffeeScript unit testing. I have a grunt task to compile the coffee files to the test folder and start PhantomJS to run the mocha tests.
Everything works fine however chai.js only indicates what test is failing and what are the expected and actual values, it does not specify what assertion is not passing in a test case. Is there any good way to print the assertion or at least the index of the assertion that is failing? I also turned on chai.Assertion.includeStack
however that only shows the line number in the JavaScript file that is not that helpful for the CoffeeScript tests.
FizzBuzzTest.coffee
fizz = new FizzBuzz()
describe "Print numbers from 1 to 100", ->
it "First 10 digits from 1 to 5", ->
result = fizz.do()
arr = result.split(fizz.Delimiter)
expect(arr[0]).to.equal("1")
expect(arr[1]).to.equal("2")
expect(arr[2]).to.equal(fizz.Fizz)
expect(arr[3]).to.equal("3") # this assertion should fail
expect(arr[4]).to.equal(fizz.Buzz)
Executing tests
$ grunt test
Running "mocha:run" (mocha) task
Testing: Content/runner.html
Print numbers from 1 to 100
✓ First 10 digits from 1 to 5
1) Last 10 digits from 95 to 100
✓ Print FizzBuzz instead of number which is divisible by both 3 and 5
✓ Check number
✓ Check Fizz
✓ Check Buzz
✓ Check FizzBuzz
✓ Check if > 100 then null
✓ Check if < 1 then null
8 passing (113ms)
1 failing
1) Print numbers from 1 to 100 Last 10 digits from 95 to 100:
AssertionError: expected true to be false
at file:///Users/milan/Sites/CoffeeTests/Content/js-libs/chai/chai.js:918
at file:///Users/milan/Sites/CoffeeTests/Content/js-libs/chai/chai.js:1159
at file:///Users/milan/Sites/CoffeeTests/Content/js-libs/chai/chai.js:3563
>> 1/9 tests failed (0.11s)
Warning: Task "mocha:run" failed. Use --force to continue.
Aborted due to warnings.
Question: Is there a good way to set chai.js to be more specific about where the AssertionError happened?
Like: AssertionError: expected true to be false in line expect(arr[3]).to.equal("3")
Thank you.
Solution
If no one comes up with a more sophisticated solution to make chai.Assertion.includeStack
work nicely with CoffeeScript code, you can always pass messages to some of the functions in the expect
interface:
it("bluh", function () {
chai.expect(false).to.be.equal(true, "here");
});
The "here"
string is a message that will be output with the error message when the assertion fails. Take a look at the documentation though because not all functions take an optional message. I first wanted to use to.be.true
above but the true
method does not take an optional message.
The assert
interface supports optional messages on more functions than the expect
interface does.