Javascript 如何使用should.js作为全局变量:
我正在尝试使用mocha和should.js编写一些单元测试,因为我希望每个单元测试的格式保持不变,并且每个单元测试都需要should.js来验证对象的正确性。我怎样才能使它成为全局变量,这样我就不需要在每个测试文件上都使用should.js了Javascript 如何使用should.js作为全局变量:,javascript,node.js,global-variables,mocha.js,should.js,Javascript,Node.js,Global Variables,Mocha.js,Should.js,我正在尝试使用mocha和should.js编写一些单元测试,因为我希望每个单元测试的格式保持不变,并且每个单元测试都需要should.js来验证对象的正确性。我怎样才能使它成为全局变量,这样我就不需要在每个测试文件上都使用should.js了 global.should = require('should'); describe('try gloabl'), () => { it('should work'), () => { let user = { name: 't
global.should = require('should');
describe('try gloabl'), () => {
it('should work'), () => {
let user = { name: 'test'};
global.should(user).have.property('name', 'test');
});
});
#error, global.should is not a function
如果我用这个。它起作用了
const should = require('should');
should = require('should');
describe('try gloabl'), () => {
it('should work'), () => {
let user = { name: 'test'};
global.should(user).have.property('name', 'test');
});
});
首先,
我已经厌倦了编写“require”
是使用全局变量的最糟糕的原因。使用require
是一种常规的处理方式,这与任何其他语言都没有什么不同,在这些语言中,您必须在每个文件中使用导入
或键入。它只是使以后更容易理解代码所做的事情。
有关详细说明,请参阅
现在,也就是说,当需要should
时,模块实际上将自身附加到全局变量,并使描述,它
和should
可访问的方法
index.js
require('should');
describe('try global', () => {
it('should work with global', () => {
let user = { name: 'test' };
global.should(user).have.property('name', 'test');
});
it('should work without global', () => {
let user = { name: 'test' };
should(user).have.property('name', 'test');
});
});
//////
mocha ./index.js
try global
√ should work with global
√ should work without global
2 passing (11ms)
我修复了代码中的输入错误(例如,从description
和it
函数中删除额外的)
,当使用mocha./index.js
运行时,此代码工作正常。确保已使用npm i-g mocha
安装mocha
,以使该模块在CLI中可用