[英]How to use should.js as global variable:
I am trying to write some unit test that using mocha and should.js since I would like to keep format for each of my unit test the same and each unit test require should.js to verify proerpty of object. 我试图使用mocha和should.js编写一些单元测试,因为我想保持每个单元测试的格式相同,并且每个单元测试都需要should.js来验证对象的属性。 How can I make it as globally variable so I do not need to require should.js on each test file so far I have tried 我如何才能使其成为全局变量,所以到目前为止,我已经尝试过在每个测试文件上都不需要require.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
and if i use this. 如果我用这个。 it works 有用
const should = require('should');
should = require('should');
describe('try gloabl'), () => {
it('should work'), () => {
let user = { name: 'test'};
global.should(user).have.property('name', 'test');
});
});
First of all, I'm tired of writing "require"
is the worst reason to use the GLOBAL variable. 首先, I'm tired of writing "require"
是使用GLOBAL变量的最糟糕的原因。 There is a reason that using require
is the conventional way of doing things, and it is not different from any other language where you have to import
or type using
in each and every file. 有一个原因,使用require
是常规的处理方式,它与您必须在每个文件中import
或键入using
任何其他语言并无不同。 It just makes it easier to understand what the code is doing later on. 它只是使以后理解代码的作用变得更加容易。 See this for further explanation. 请参阅此内容以获取更多说明。
Now, that said, when requiring should
, the module actually attaches itself to the GLOBAL variable, and makes describe
, it
and should
accessible methods. 现在,这就是说,在需要should
,模块实际上it
自身附加到GLOBAL变量,并使其describe
, it
和should
可访问的方法。
index.js 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)
I fixed the typos in your code (eg. Removing the extra )
from describe
and it
function), and this code works just fine when running with mocha ./index.js
. 我固定的输入错误代码(如删除多余的)
从describe
和it
的功能),并与运行时,此代码的工作就好了mocha ./index.js
。 Make sure you have install mocha
with npm i -g mocha
to make the module available in the CLI. 确保已使用npm i -g mocha
安装了mocha
,以使模块在CLI中可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.