Search code examples
unit-testingmocha.jsassertchai

Mocha.js test with Chai.js not working in asserting numeric values


I am facing a problem in writing a test case using Mocha and Chai. In the following code value of n is 1. I checked it using console.log(). Though I am testing this value against 0 the test is still passing. Actually it doesn't matter against what value n is tested, the test is passing anyway. What is the problem in it? Can anyone help?

it("Should have 1 variables", function(){                                    
    var variable_count = require("../../lib/variable_count").variable_count; 
    var file = __dirname + '/cases/case_3.json';                             
    jsonfile.readFile(file, function(err, obj) {                                                            
        var n = variable_count(obj);                                                                        
        expect(n).to.equal(0);                                                                         
        assert.strictEqual(n, 0);                                                                           
    });                                                                                                     
});

Solution

  • The issue is that your code is asynchronous (because of jsonfile.readFile()), but your test is synchronous.

    To make the test asynchronous, so it waits for a result, you can use the following:

    it("Should have 1 variables", function(done) {
      var variable_count = require("../../lib/variable_count").variable_count;
      var file = __dirname + '/cases/case_3.json';
      jsonfile.readFile(file, function(err, obj) {
        var n = variable_count(obj);
        expect(n).to.equal(0);
        assert.strictEqual(n, 0);
        done();
      });
    });
    

    More info here.