我正在尝试使用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)
})
})
})
和test/array.js
文件。 Mocha安装了
$ npm install -g mocha
当我跑步时
$ mocha
我收到此错误:
$ 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)
答案 0 :(得分:74)
expect
确实未定义,因为您从未定义它。
(我推荐chai)
npm install chai
然后
(参见Amit Choukroune的评论指出实际上需要柴)
然后
var expect = chai.expect;
答案 1 :(得分:8)
尝试
首先,在终端
npm install expect.js
在您的代码中:
var expect = require('expect');
答案 2 :(得分:2)
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));
});
});
});
答案 3 :(得分:1)
按照其他帖子的建议安装Chai后,使用es6语法,您应该将导入放在顶部
import {expect} from 'Chai';
答案 4 :(得分:1)
为了在使用expect
的同时全局公开chai
,应通过配置为您首选的测试库加载以下内容:
require('chai/register-assert'); // Using Assert style
require('chai/register-expect'); // Using Expect style
require('chai/register-should'); // Using Should style
例如:
npx mocha --config .mocharc.js *.spec.js
答案 5 :(得分:0)
如果您使用Mocha for TDD
,请安装Expect.js或Chai.js所以,请npm install expect
或npm install chai
答案 6 :(得分:0)
在我的用例中,我通过karma
运行了一个mocha规范。解决方案是为我的测试框架库安装karma集成:
npm install karma-mocha --save-dev
npm install karma-sinon-chai --save-dev
...还要将框架添加到我的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'
}
}
})
}
希望这有助于其他人。
答案 7 :(得分:0)
可以将此脚本标记添加到html文件中
<script src="https://unpkg.com/expect@%3C21/umd/expect.min.js"></script>
或安装软件包
npm install chai or expect
答案 8 :(得分:0)
创建文件chaiexpections.js并声明Expect为全局
'use strict';
// Configure chai
global.expect = require('chai').expect;
现在将其传递到黄瓜选择下的配置文件中,要求
cucumberOpts: {
require: ['./testsuites/*.js','./chaiexpections.js','./commons/hooks.js']
//tags: [],
strict: true,
format: [],
'dry-run': false,
compiler: [],
format: 'json:results.json',
},
这避免了必须在每个步骤定义中声明chai异常的开销