Search code examples
javascriptunit-testingmocha.jsassert

How can my JavaScript assert library return a pass?


I am working on a custom Javascript assert library, primarily for use in test runners like Mocha.

The library works fine when the test fails, by throwing an Error. However, I can't figure out how to make the library return a "pass", when there's no Error to throw.

I have tried reading through the source of other libraries like Should and Chai, but haven't been able to locate this aspect.

Here is my assert library, my-assert-lib.js:

module.exports = function(input){
    var methods = {
        compare: function(comparison){
            if(input != comparison){
                throw new Error("The comparison string didn't match")
            }
            else{
                return
            }
        }

    }
    return methods
}

Here is my test.js, which I'm executing with Mocha:

var myAssertLib = require("./my-assert-lib.js")("correct");

describe("The comparison string", function(){
    it('should match the library input', function(doc) {
        myAssertLib.compare("incorrect")
    });

    it('should match the library input', function(doc) {
        myAssertLib.compare("correct")
    });
})

I get these results:

  0 passing (2s)
  2 failing

  1) The comparison string
       should match the library input:
     Error: The comparison string didn't match
      at Object.compare (my-assert-lib.js:5:23)
      at Context.<anonymous> (test.js:10:21)

  2) The comparison string
       should match the library input:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

The first test exits immediately, as it should. However, the second test times out. What does my-assert-lib.js need to do when there's nothing to throw and the test runner should continue?


Solution

  • I can't say why, but mocha is expecting you to call the done function.

    Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

    Doing so yields one pass and one fail, as expected.

    describe("The comparison string", function(){
        it('should match the library input', function(done) {
            myAssertLib.compare("incorrect")
            done()
        })
        it('should match the library input', function(done) {
            myAssertLib.compare("correct")
            done()
        })
    })
    
    >   The comparison string
    >     1) should match the library input
    >     ✓ should match the library input
    > 
    > 
    >   1 passing (14ms)   1 failing
    > 
    >   1) The comparison string
    >        should match the library input:
    >      Error: The comparison string didn't match
    >       at Object.compare (assertLib.js:7:23)
    >       at Context.<anonymous> (test.js:7:21)