Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocha Test Fails with AssertionError

In JUnit (Java) the result of a unit test is either a succes, failure or error.

When i try to run a test with Mocha i either get a succes or assertion error.

Is is normally to get an AssertionError for failure tests? (shouldn't it just be called an failure and not an error?)

AssertionError: -1 == 2 + expected - actual

What about testing asynchronous code? When my tests fail i get an Uncaught eror? Is that normal?

Like this:

Uncaught Error: expected 200 to equal 201

like image 471
user3452075 Avatar asked May 28 '15 12:05

user3452075


People also ask

Do mocha tests run sequentially?

js and in the browser. It's designed for testing both synchronous and asynchronous code with a very simple interface. Mocha runs tests serially to deliver flexible and accurate reporting while mapping uncaught exceptions to their corresponding test cases.

How do you run a single test case in mocha?

Learn how to run only one test with Mocha To run a single test (as defined in it() ), you can simply call the only() method on it in the following way: it. only('...', function () { // only this test will run... });

Is Mocha a runner test?

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.


1 Answers

What you are describing is the normal behavior for Mocha. This code illustrates what happens if you do not try to trap exceptions in asynchronous code (even raised by assertion failures) and what you can do if you want to avoid the uncaught exception message:

var assert = require("assert");

it("fails with uncaught exception", function (done) {
    setTimeout(function () {
        assert.equal(1, 2);
        done();
    }, 1000);
});

it("fails with assertion error", function (done) {
    setTimeout(function () {
        try {
            assert.equal(1, 2);
            done();
        }
        catch (e) {
            done(e);
        }
    }, 1000);
});

The code above produces this output:

  1) fails
  2) fails

  0 passing (2s)
  2 failing

  1)  fails:
     Uncaught AssertionError: 1 == 2
      at null._onTimeout (/tmp/t2/test.js:5:16)
      at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

  2)  fails:
     AssertionError: 1 == 2
      at null._onTimeout (/tmp/t2/test.js:13:20)
      at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
like image 136
Louis Avatar answered Sep 30 '22 06:09

Louis