Jasmine - How To Mock Global Variables & Functions

Viewed 3985

I have a script I would like to test that includes global variables with some of them being initialized with functions calls. For example

var g_count = 0;
var g_util = addLibrary( "util.lib" );

I would like to mock both g_count and g_util

If I have a function call within my testing function I can easily mock it with addLibrary = jasmine.createSpy(); but once it is in global scope, the mock fails and I get an error message

Reference Error: addLibrary is not defined.

Edit: I figured out how to mock the variable. I added it to a global property,

var globals = {
    g_count : null
}

Exported it

module.exports = {
    globals: globals
}

Then spied on it

spyOnProperty(util.globals, 'g_count').and.returnValue(5);

I still can't figure out the addLibrary function

1 Answers

I fixed the error for the addLibrary. Since it is used to initialize a global variable it was being called when I required the script. Adding addLibrary = jasmine.createSpy(); above the require(...) fixed it.

Related