如何解决"ReferenceError:expect is not defined"错误消息?

sen*_*rio 54 javascript mocha.js node.js

我试图用mocha测试Javascript.我有这段代码:

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)
        })
    })
})
Run Code Online (Sandbox Code Playgroud)

和一个test/array.js文件.摩卡安装了

$ npm install -g mocha
Run Code Online (Sandbox Code Playgroud)

我跑的时候

$ mocha
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

$ 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)
Run Code Online (Sandbox Code Playgroud)

Dan*_*den 79

摩卡是一个测试框架; 你需要提供自己的断言库作为https://mochajs.org/#assertions状态.因此,expect确实未定义,因为您从未定义它.

(我推荐)

npm install chai
Run Code Online (Sandbox Code Playgroud)

然后

(见Amit Choukroune的评论指出实际上需要柴)

然后

var expect = chai.expect;
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用`var expect = require('chai').期望,` (15认同)
  • 或者`var expect =(typeof require ==='undefined')?chai.expect:require('chai').expect;`如果你想在浏览器的页面上用mocha运行测试. (4认同)

Pau*_*Rad 8

尝试

首先,在终端

npm install expect.js

在你的代码中:

var expect = require('expect');
Run Code Online (Sandbox Code Playgroud)


dmc*_*chk 7

按照其他帖子的建议安装 Chai 后,使用 es6 语法,您应该将导入放在顶部

import {expect} from 'chai';
Run Code Online (Sandbox Code Playgroud)


Kri*_*gid 6

就我而言,我正在使用JEST Test Cases. 我将所有test.js文件放入下 pages/一个文件结构的文件夹中。

因此,通过将所有test.js文件从pages文件夹移动next file structure到内部__test__文件夹外部或root of the folder