简体   繁体   中英

How to test globals with Mocha?

When testing with Mocha, how dose one load foo.js so that the foo-test.js can test global variables such as giveMeFive()?

foo.js:

function giveMeFive() {
    return 'High five!');
}

foo-test.js:

describe('#convertNumberToDollar()', function() {
  it('should get a successful high five', () => {
    assert.ok( giveMeFive() === 'High five!', ' successful high five.' );
  });
});

It would be ideal if the solution can be automated via Bamboo.

You can just use import * as thisNameDoesntMatter from 'foo' or, using es5 style (which is cleaner in this case), require('foo') and globals defined in that file will be available on the global scope.

For instance, if you define the following JavaScript file:

//test.js

aGlobalVariable = 'someValue';

let aLocalVariable = 'anotherValue';

export default aLocalVariable;

This is the code Babel will generate (using the es2015 preset and the "node" environment):

//test-compiled.js
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
global.aGlobalVariable = 'someValue';

var aLocalVariable = 'anotherValue';

exports.default = aLocalVariable;

As you can see, the aGlobalVariable declaration is kept in the module. As the entire compiled file will be evaluated when it's imported, aGlobalVariable will be available on the global scope whenever you import this module (if you chose the "browser" environment, it would be defined on window ). You don't need to explicitly request the globals to be imported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM