繁体   English   中英

如何使用Mocha测试全局变量?

[英]How to test globals with Mocha?

在使用Mocha进行测试时,如何加载foo.js,以便foo-test.js可以测试全局变量,例如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.' );
  });
});

如果解决方案可以通过Bamboo自动化,那将是理想的选择。

您可以使用import * as thisNameDoesntMatter from 'foo'或者使用es5样式(在这种情况下更干净), require('foo')并且该文件中定义的全局变量将在全局范围内可用。

例如,如果您定义以下JavaScript文件:

//test.js

aGlobalVariable = 'someValue';

let aLocalVariable = 'anotherValue';

export default aLocalVariable;

这是Babel将生成的代码(使用es2015预设和"node"环境):

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

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

var aLocalVariable = 'anotherValue';

exports.default = aLocalVariable;

如您所见, aGlobalVariable声明保留在模块中。 由于整个编译文件将在导入时进行评估,因此无论何时导入此模块, aGlobalVariable都将在全局范围内可用(如果选择"browser"环境,则将在window定义)。 您不需要显式请求导入全局变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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