使用jasmine-node监视全局函数 [英] spying upon a global function using jasmine-node

查看:166
本文介绍了使用jasmine-node监视全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using jasmine-node to do unit testing on javascript code. I have a number of global functions which I would like to spyOn and allow the call to make it though to the original implementation. See the code below as an example.

由于某种原因我无法解释,我发现错误globalFunction()方法不存在。

For a reason I cannot explain, I am seeing an error "globalFunction() method does not exist".

有人可以告诉我为什么茉莉花无法找到这个我理解为全球范围的globalFunction方法。

Can someone tell me why jasmine is not able to find this globalFunction method which I understand to be in global scope.

我很感激帮助

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的输出

Here is the output of 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 关键字以使其成为全局。

Your globalFunction not global in fact. Remove var keyword to make it global.

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




在浏览器中,顶级范围是全局范围。这意味着在浏览器中,如果您处于全局范围,则var将定义全局变量。在Node中,这是不同的。顶级范围不是全球范围; Node模块中的var内容将是该模块的本地内容。

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.

这篇关于使用jasmine-node监视全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆