【问题标题】:How to use should.js as global variable:如何使用 should.js 作为全局变量:
【发布时间】:2018-09-18 18:10:29
【问题描述】:

我正在尝试使用 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');
  });
});

【问题讨论】:

    标签: javascript node.js global-variables mocha.js should.js


    【解决方案1】:

    首先,I'm tired of writing "require" 是使用 GLOBAL 变量的最糟糕原因。使用require 是传统的处理方式是有原因的,它与您必须在每个文件中使用import 或键入using 的任何其他语言没有什么不同。它只是让以后更容易理解代码在做什么。 更多解释请见this

    现在,也就是说,当需要 should 时,模块实际上将自己附加到 GLOBAL 变量,并使 describeitshould 可访问方法。

    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)
    

    我修正了您代码中的拼写错误(例如,从 describeit 函数中删除了额外的 )),并且此代码在与 mocha ./index.js 一起运行时运行良好。确保您已安装 mochanpm i -g mocha 以使该模块在 CLI 中可用。

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      相关资源
      最近更新 更多