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

Javascriptnode.jsmocha.js

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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;

Solution 2 - Javascript

Try

First, in the terminal

npm install expect.js

And in your code:

var expect = require('expect');

Solution 3 - Javascript

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 4 - Javascript

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 5 - Javascript

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) {
    config.set({
        browsers: ['Chrome'],
        frameworks: ['mocha', 'sinon-chai'],
        files: [
            '.tmp/**/*.spec.js'
        ],
        client: {
            chai: {
                includeStack: true
            },
            mocha: {
                reporter: 'html',
                ui: 'bdd'
            }
        }
    })
}

Hope this helps someone else.

Solution 6 - Javascript

In order to expose expect globally, while using chai, following should be loaded by means of configuration for your prefered testing library:

require('chai/register-assert');  // Using Assert style
require('chai/register-expect');  // Using Expect style
require('chai/register-should');  // Using Should style

For example:

npx mocha --config .mocharc.js *.spec.js

Solution 7 - Javascript

In my case i was using JEST Test Cases. and i put all test.js file inside pages/ folder of next file structure.

So solve my issue by move all test.js file from pages folder of next file structure to inside __test__ folder outside or root of the folder

Solution 8 - Javascript

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

So, do npm install expect or npm install chai

Solution 9 - Javascript

Either add this script tag in html file

<script src="https://unpkg.com/expect@%3C21/umd/expect.min.js"></script>

or install package

npm install chai or expect

Solution 10 - Javascript

Create a file chaiexpections.js and declare expect as global

'use strict';

// Configure chai
global.expect = require('chai').expect;

Now pass it in config file under cucumberopts, require

cucumberOpts: {
    require: ['./testsuites/*.js','./chaiexpections.js','./commons/hooks.js']
    //tags: [],
    strict: true,    
    format: [],  
    'dry-run': false,           
    compiler: [],
    format: 'json:results.json',   
  },

This prevents the overhead of having to declare chai exception in each stepdefinition

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsensorarioView Question on Stackoverflow
Solution 1 - JavascriptDan HeberdenView Answer on Stackoverflow
Solution 2 - JavascriptPaul RadView Answer on Stackoverflow
Solution 3 - JavascriptdmchkView Answer on Stackoverflow
Solution 4 - JavascriptshaelView Answer on Stackoverflow
Solution 5 - JavascriptRMorriseyView Answer on Stackoverflow
Solution 6 - JavascriptmicrubView Answer on Stackoverflow
Solution 7 - JavascriptKrishna JangidView Answer on Stackoverflow
Solution 8 - JavascriptALoK VeRMaView Answer on Stackoverflow
Solution 9 - JavascriptASHISH RView Answer on Stackoverflow
Solution 10 - JavascriptPDHideView Answer on Stackoverflow