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

sensorario picture sensorario · Oct 4, 2013 · Viewed 60.2k times · Source

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() {
            expect([1,2,3].indexOf(4)).to.equal(-1)
        })
    })
})

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.<anonymous> (/Users/simonegentili/Desktop/Javascipt Best Practice/test/array.js:4:4)
  at Test.Runnable.run (/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)

Answer

Dan Heberden picture Dan Heberden · Oct 4, 2013

Mocha is a test framework; you need to provide your own assertion lib as https://mochajs.org/#assertions states. Thus, expect is indeed undefined because you never defined it.

(I recommend chai)

npm install chai

then

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

then

var expect = chai.expect;