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)
To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.
Reference errors in Javascript are mainly thrown when an attempt is made to reference a variable that does not exist or is out of scope. Therefore, in the majority of cases, a ReferenceError can be fixed by making sure that the referenced variable is defined correctly and is being called in the correct scope.
The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced. ReferenceError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage() .
The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.
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;
Try
First, in the terminal
npm install expect.js
And in your code:
var expect = require('expect');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With