user502014
user502014

Reputation: 2331

Jasmine + test external dependency

I was wondering the best way to use jasmine to test external dependencies.

For example I have an overlay module that purely shows and hides a background mask:

function Overlay () {

}

Overlay.prototype.show = function () {

}

Overlay.prototype.hide = function () {

}

This has complete Jasmine unit tests set up.

I then have another module Dialog that uses the overlay Module:

function Dialog () {

}

Dialog.prototype.show() {
 //do dialog stuff here, then show overlay
 var overlay = new Overlay();
 overlay.show();
}

I have Jasmine tests that test all the dialog apart from the overlay. With the assumption that the overlay unit tests are setup and passing does the dialog test just need to ensure that var overlay is defined and that its show method has been called?

For separation of concerns is this the best way to do this?

Thanks in advance

Upvotes: 2

Views: 1352

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 110892

Best way would be to inject an instance of your overlay into the constructor of your Dialog.

function Dialog (overlay) {
  this.overlay = overlay:
}

Dialog.prototype.show() {
 this.overlay.show();
}

In your test you can then simply inject a spy.

var overlay = {show: jasmine.createSpy()};
var dialog = new Dialog(overlay);
dialog.show();
expect(overlay.show). toHaveBeenCalled();

Another way would be to spy on the global Overlay function and return a object with spy on the show function.

var overlay = {show: jasmine.createSpy()};
jasmine.spyOn(Overlay, 'show').andReturn(overlay);
var dialog = new Dialog(overlay);
dialog.show();
expect(overlay.show). toHaveBeenCalled();

Upvotes: 3

Related Questions