I'm new to Jasmine and have just started using it. I have a library js file with lots of functions which are not associated with any object (i.e. are global). How do I go about spying on these functions?
I tried using window/document as the object, but the spy did not work even though the function was called. I also tried wrapping it in a fake object as follows :
var fakeElement = {};
fakeElement.fakeMethod = myFunctionName;
spyOn(fakeElement, "fakeMethod");
and test with
expect(fakeElement.fakeMethod).toHaveBeenCalled();
This does not work either as the spy did not work
This question is related to
javascript
unit-testing
jasmine
TypeScript users:
I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.
In the test file, convert the import of the function from this:
import {foo} from '../foo_functions';
x = foo(y);
To this:
import * as FooFunctions from '../foo_functions';
x = FooFunctions.foo(y);
Then you can spy on FooFunctions.foo
:)
spyOn(FooFunctions, 'foo').and.callFake(...);
// ...
expect(FooFunctions.foo).toHaveBeenCalled();
import * as saveAsFunctions from 'file-saver';
..........
.......
let saveAs;
beforeEach(() => {
saveAs = jasmine.createSpy('saveAs');
})
it('should generate the excel on sample request details page', () => {
spyOn(saveAsFunctions, 'saveAs').and.callFake(saveAs);
expect(saveAsFunctions.saveAs).toHaveBeenCalled();
})
This worked for me.
My answer differs slightly to @FlavorScape in that I had a single (default export) function in the imported module, I did the following:
import * as functionToTest from 'whatever-lib';
const fooSpy = spyOn(functionToTest, 'default');
A very simple way:
import * as myFunctionContainer from 'whatever-lib';
const fooSpy = spyOn(myFunctionContainer, 'myFunc');
There is 2 alternative which I use (for jasmine 2)
This one is not quite explicit because it seems that the function is actually a fake.
test = createSpy().and.callFake(test);
The second more verbose, more explicit, and "cleaner":
test = createSpy('testSpy', test).and.callThrough();
-> jasmine source code to see the second argument
Source: Stackoverflow.com