2

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.    
4

1 回答 1

3

globalFunction实际上,您不是全球性的。删除var关键字以使其全局化。

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

在浏览器中,顶级作用域是全局作用域。这意味着在浏览器中,如果您在全局范围 var 中,某些东西将定义一个全局变量。在 Node 中,这是不同的。顶级范围不是全局范围;var 节点模块中的某些内容将是该模块的本地内容。

于 2012-09-03T17:37:31.300 回答