我很难弄清楚如何访问通常作为浏览器中窗口对象的方法提供的函数。我正在使用 Karma、Headless Chrome 和 Jasmine。
这里是我的问题的简化:
我有一个名为 add-numbers-together.js
的模块:
function addTogether(a, b) {
return a + b;
}
(function(){
addTogether(2,5);
})();
Jasmine 测试正在对此进行测试:
describe('add-numbers-together.js', function() {
it('Should add numbers together', function() {
require('module/add-numbers-together');
console.info(window.addTogether);
});
});
require 语句肯定可以检索模块,我已经测试过了。
我期待 console.info 打印出函数的定义,就像我在实际浏览器中执行此操作时的情况一样,但此 console.info 返回 undefined
。 这是为什么?以及在测试中需要模块后如何访问 addTogether 函数?
我猜这是 Jasmine 或 Headless Chrome 的一些怪癖,但无论我多么努力地搜索,我都找不到答案!
另外,请注意:我不想向模块本身添加任何测试代码,这不是我的选择。
最佳答案
我稍微更改了测试以检查该函数不是 undefined
,但是无论使用 Chrome
还是 ChromeHeadless
作为浏览器,它都失败了。
describe('add-numbers-together.js', function() {
it('Should add numbers together', function() {
require('module/add-numbers-together');
expect(window.addTogether).not.toBeUndefined();
});
});
要使此测试的某个版本通过,您有多种选择:
- 使被测代码成为真正的模块并
导出
函数,然后将测试更改为导入
该模块(推荐)。如果使用 AMD,这也可以是define
和require
。 - 配置您的build设置以在不更改代码的情况下强制从该模块全局
导出
(webpack 可以做到这一点,这有点像 hackkey,但如果您不能编辑该脚本,它就可以工作) .这通常仅通过第 3 方脚本完成。 - 将测试文件中的脚本内容放在测试代码上方(不推荐,因为你是复制粘贴,更改不会同步)。
- 加载被测脚本,然后在夹具标记中加载测试(有效,但有点蹩脚,因为你的测试夹具 HTML 现在硬编码脚本引用)。
这是为选项 #1 使用函数的 export
重写的被测代码。
export function addTogether(a, b) {
return a + b;
}
(function () {
addTogether(2, 5);
})();
这里是为选项 #1 重写的测试,其中包含被测模块的 import
。
import * as addNumbersTogether from 'add-numbers-together';
describe('add-numbers-together.js', function () {
it('Should add numbers together', function () {
expect(addNumbersTogether.addTogether).not.toBeUndefined();
});
});
关于javascript - 使用 Jasmine 和 Headless Chrome 时,全局函数在 Window 对象中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951532/