Pavel S.
Pavel S.

Reputation: 12322

Chai exports are not found in Mocha test

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?

Upvotes: 1

Views: 5831

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 145994

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);

Upvotes: 4

Related Questions