How can I solve “ReferenceError: expect is not defined” error message?


How can I solve “ReferenceError: expect is not defined” error message?

I am trying to test Javascript with mocha. I’ve this snippet of code:
describe(‘Array’, function() {
describe(‘indexOf()’, function() {
it(“dovrebbe tornare -1 quando l’elemento non è presente”, function() {

and a test/array.js file. Mocha was installed with
$ npm install -g mocha

When I run
$ mocha

I get this error:
$ mocha

0 passing (5ms)
1 failing

1) Array indexOf() dovrebbe tornare -1 quando l’elemento non è presente:
ReferenceError: expect is not defined
at Context. (/Users/simonegentili/Desktop/Javascipt Best Practice/test/array.js:4:4)
at (/usr/local/lib/node_modules/mocha/lib/runnable.js:211:32)
at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:358:10)
at /usr/local/lib/node_modules/mocha/lib/runner.js:404:12
at next (/usr/local/lib/node_modules/mocha/lib/runner.js:284:14)
at /usr/local/lib/node_modules/mocha/lib/runner.js:293:7
at next (/usr/local/lib/node_modules/mocha/lib/runner.js:237:23)
at Object._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:261:5)
at processImmediate [as _immediateCallback] (timers.js:317:15)


Solution 1:

Mocha is a test framework; you need to provide your own assertion lib as states. Thus, expect is indeed undefined because you never defined it.

(I recommend chai)

npm install chai


(see Amit Choukroune’s comment pointing out to actually require chai)


var expect = chai.expect;

Solution 2:


First, in the terminal

npm install expect.js

And in your code:

var expect = require('expect');

Solution 3:

let chai = require('chai');

var assert = chai.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(4));

Solution 4:

After you install Chai as other posts suggest, with the es6 syntax you should put the import at the top

import {expect} from 'Chai';

Solution 5:

Install Expect.js or Chai.js if you are using Mocha for TDD

So, do npm install expect or npm install chai

Solution 6:

In my use case, I was running a mocha spec through karma. The solution was to install the karma integrations for my test framework libs:

npm install karma-mocha --save-dev
npm install karma-sinon-chai --save-dev

…and also to add the frameworks to my karma.conf.js:

module.exports = function(config) {
        browsers: ['Chrome'],
        frameworks: ['mocha', 'sinon-chai'],
        files: [
        client: {
            chai: {
                includeStack: true
            mocha: {
                reporter: 'html',
                ui: 'bdd'

Hope this helps someone else.