我正在尝试写一些使用mocha和should.js的单元测试,因为我想保持每个单元测试的格式相同,并且每个单元测试都需要should.js来验证对象的属性。如何才能将其设置为全局变量,这样就不需要对每个测试文件都使用should.js
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');
});
});发布于 2018-09-18 18:10:30
首先,I'm tired of writing "require"是使用全局变量的最糟糕的原因。使用require是一种传统的操作方式,这是有原因的,而且它与任何其他语言没有什么不同,在这些语言中,您必须在每个文件中使用import或键入using。这只会让我们更容易理解以后代码在做什么。有关详细说明,请参阅this。
现在,也就是说,当需要should时,该模块实际上将自己附加到全局变量,并使describe、it和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)我修正了你代码中的拼写错误(例如:从describe和it函数中删除额外的) ),并且此代码在与mocha ./index.js一起运行时工作得很好。确保已安装带有npm i -g mocha的mocha,以使该模块在命令行界面中可用。
https://stackoverflow.com/questions/52376285
复制相似问题