81

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)
Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
sensorario
  • 20,262
  • 30
  • 97
  • 159

11 Answers11

105

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;
starcwl
  • 396
  • 2
  • 9
Dan Heberden
  • 10,990
  • 3
  • 33
  • 29
12

Try

First, in the terminal

npm install expect.js

And in your code:

var expect = require('expect');
Keatinge
  • 4,330
  • 6
  • 25
  • 44
Paul Rad
  • 4,820
  • 1
  • 22
  • 23
10

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

import {expect} from 'chai';
dmchk
  • 608
  • 6
  • 8
4

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

Krishna Jangid
  • 4,961
  • 5
  • 27
  • 33
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));
    });
  });
});
AntonioGarcía
  • 1,140
  • 2
  • 15
  • 25
shael
  • 41
  • 4
3

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

micrub
  • 740
  • 8
  • 17
1

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.

RMorrisey
  • 7,637
  • 9
  • 53
  • 71
0

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

So, do npm install expect or npm install chai

John Slegers
  • 45,213
  • 22
  • 199
  • 169
ALoK VeRMa
  • 91
  • 6
0

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
ASHISH R
  • 4,043
  • 1
  • 20
  • 16
0

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

PDHide
  • 18,113
  • 2
  • 31
  • 46
0

In my case I was importing setupTests.ts file inside index.tsx so when react app starts the development server it couldn't find the test related dependencies .

setupTests.ts

import "@testing-library/jest-dom";

I did solve this issue the easiest way possible providing jest a config file named jest.config.js and removed import "setupTests"; from index.tsx file .

module.exports = {
  setupFilesAfterEnv: ["./src/setupTests.ts"],
};
Mehdi Faraji
  • 2,574
  • 8
  • 28
  • 76