1

I have created simple Mocha test. It works perfectly when Node "assert" module is used. I run it from command line (Mocha is installed as a global node module):

$ mocha myTest.js

․

1 test complete (6 ms)

The script looks like this:

var assert = require("assert")
describe('Array', function(){
    describe('#indexOf()', function(){
        it('should return -1 when the value is not present', function(){
            assert.equal(-1, [1,2,3].indexOf(5));
            assert.equal(-1, [1,2,3].indexOf(0));
        })
    })
})

Well, I tried to add Chai instead of assert library. I installed it first:

npm install chai

So, the directory node_modules has been created in my project. Great so far. Then, I altered the script to use Chai:

var chai = require("chai");

describe('Array', function(){
    describe('#indexOf()', function(){
        it('should return -1 when the value is not present', function(){
            [1,2,3].indexOf(5).should.equal(-1);
            expect([1,2,3].indexOf(5)).to.equal(-1);
            assert.equal([1,2,3].indexOf(5),-1);
        })
    })
});

It does not work, Mocha test fails with TypeError:

TypeError: Cannot call method 'equal' of undefined

I assume Chai did not define should so it is undefined.

How is this possible?

How can I make my tests run with Chai? I have tried to install Chai globally with no effect. I also ran the script with -r chai with no effect as well.

Apparently, Chai module is loaded, but does not define the variables (Object.prototype properties). How can I fix this?

Pavel S.
  • 11,892
  • 18
  • 75
  • 113

1 Answers1

4
var expect = require('chai').expect;

That will get your expect calls working. However, you also have a should call which comes from a different library entirely, so change

[1,2,3].indexOf(5).should.equal(-1);

to

expect([1,2,3].indexOf(5)).to.equal(-1);
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Yes. This is the design decision the CommonJS community has made. Explicitly declared dependencies, even if verbose, are preferable to implicit dependencies. – Peter Lyons Dec 14 '15 at 14:00
  • In my case, I just get a message saying that 'require' is undefined. I am running mocha via karma in gulp – RMorrisey May 17 '16 at 18:12
  • This question is about node.js. If you are running in a browser, you'll need a module bundler such as browserify or webpack if you want to use commonjs `require`. Otherwise, just follow the chai directions for loading it into the browser global namespace and use it directly without require. – Peter Lyons May 23 '16 at 13:47