I have a JavaScript file main_one.js
which requires another JavaScript file helper.js
.
helper.js
warp = {
postThisEvent: function(a) {
// some operation on a
}
};
main_one.js
var Helper = require('path/helper.js');
// some steps
Helper.warp.postThisEvent(event);
I want to capture event
using Jasmine. How do I create my spy object for capturing event
in postThisEvent()
?
In the Jasmine test require Helper
, then spy this way:
spyOn(Helper.warp, "postThisEvent").and.callThrough();
This will replace postThisEvent
on the object Helper.warp
with a spy function. When it's called the spy will register the call and than call the original method as this was instructed by callThrough()
.
Then you can expect that postThisEvent()
was called with the expected objects this way:
expect(Helper.warp.postThisEvent).toHaveBeenCalledWith(jasmine.objectContaining({
someProperty: "someValue"
}));
jasmine.objectContaining()
is a helper that will only test that the expecte properties are present among multiple properties of the object under test.
You can also inspect complex objects directly:
expect(Helper.warp.postThisEvent.calls.mostRecent().args[0].someProperty).toBe("someValue");
Note that such a spy might not work when postThisEvent()
was saved to a variable which is then called like this:
var postThisEvent = Helper.warp.postThisEvent;
function triggering() {
postThisEvent({ someProperty: "someValue" })
}
// now a spy is created and then triggering() is called
In this case the reference to the original method cannot be reached when spying. There's no way to intercept the function/method in this case in Javascript.
See
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With