柴出口不在摩卡检验中发现

Chai exports are not found in Mocha test

本文关键字:检验 发现 摩卡 出口      更新时间:2023-09-26

我创建了一个简单的Mocha测试。当使用Node"assert"模块时,它可以完美地工作。我从命令行运行它(Mocha作为全局节点模块安装(:

$ mocha myTest.js
․
1 test complete (6 ms)

脚本如下:

var assert = require("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(5));
            assert.equal(-1, [1,2,3].indexOf(0));
        })
    })
})

嗯,我试着添加Chai而不是断言库。我先安装了它:

npm install chai

因此,node_modules目录已经在我的项目中创建。到目前为止很棒。然后,我修改了脚本以使用Chai:

var chai = require("chai");
describe('Array', function(){
    describe('#indexOf()', function(){
        it('should return -1 when the value is not present', function(){
            [1,2,3].indexOf(5).should.equal(-1);
            expect([1,2,3].indexOf(5)).to.equal(-1);
            assert.equal([1,2,3].indexOf(5),-1);
        })
    })
});

它不起作用,Mocha测试失败,TypeError:

TypeError: Cannot call method 'equal' of undefined

我认为柴没有定义应该,所以它是不定义的。

这怎么可能?

如何让我的测试与Chai一起运行?我尝试在全球范围内安装Chai,但没有效果。我还用-r chai运行了这个脚本,但没有任何效果。

显然,Chai模块已加载,但没有定义变量(Object.prototype属性(。我该怎么解决这个问题?

var expect = require('chai').expect;

这将使您的expect呼叫正常工作。但是,您也有一个完全来自不同库的should调用,因此请更改

[1,2,3].indexOf(5).should.equal(-1);

expect([1,2,3].indexOf(5)).to.equal(-1);