gpt4 book ai didi

javascript - 使用 jasmine-node 监视全局函数

转载 作者:搜寻专家 更新时间:2023-11-01 00:46:28 24 4
gpt4 key购买 nike

我正在使用 jasmine-node 对 javascript 代码进行单元测试。我有许多全局函数,我想监视它们并允许调用通过原始实现进行调用。请参阅下面的代码作为示例。

由于我无法解释的原因,我看到错误“globalFunction() 方法不存在”。

有人能告诉我为什么 jasmine 找不到这个我理解为在全局范围内的 globalFunction 方法。

感谢您的帮助

var globalFunction = function() {
console.log('globalFunction');
};

describe("A Global Function", function() {
jasmine.getEnv().addReporter(new jasmine.ConsoleReporter(console.log));
it("may be spied upon", function() {
spyOn(global,'globalFunction').andCallThrough();
globalFunction();
expect(globalFunction).toHaveBeenCalled();
});
});

这是 Jasmine Node 的输出

$ jasmine-node  --verbose test.spec.js 
Runner Started.
A Global Function : may be spied upon ...
Failed.
A Global Function: 0 of 1 passed.

A Global Function
may be spied upon

Failures:

1) may be spied upon
Message:
globalFunction() method does not exist
Stacktrace:
undefined

Finished in 0.008 seconds
1 test, 1 assertion, 1 failure


Runner Finished.
1 spec, 1 failure in 0.008s.

最佳答案

您的globalFunction 实际上不是全局的。删除 var 关键字以使其成为全局关键字。

globalFunction = function() {
console.log('globalFunction');
};

In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

关于javascript - 使用 jasmine-node 监视全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12251245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com