spying upon a global function using jasmine-node

不羁的心 提交于 2019-12-07 22:03:45

问题


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.

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

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

I appreciate the help

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();
    });
});

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.    

回答1:


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

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.



来源:https://stackoverflow.com/questions/12251245/spying-upon-a-global-function-using-jasmine-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!