0

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. 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

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');
  });
});
jacobcan118
  • 7,797
  • 12
  • 50
  • 95

1 Answers1

1

First of all, I'm tired of writing "require" is the worst reason to use the GLOBAL variable. 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. 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.

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. Make sure you have install mocha with npm i -g mocha to make the module available in the CLI.

Enslev
  • 627
  • 3
  • 14