Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture an argument passed to function in different JavaScript file using Jasmine

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()?

like image 230
tourniquet_grab Avatar asked May 09 '16 08:05

tourniquet_grab


1 Answers

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

  • Jasmine 2.4 Spies and
  • Spy inspection in the chapter Other tracking properties
like image 130
try-catch-finally Avatar answered Sep 16 '22 20:09

try-catch-finally