2

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

4

1 回答 1

3

最好的方法是将覆盖的实例注入对话框的构造函数中。

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

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

在您的测试中,您可以简单地注入一个间谍。

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

另一种方法是监视全局Overlay函数并返回一个带有 spyshow函数的对象。

var overlay = {show: jasmine.createSpy()};
jasmine.spyOn(Overlay, 'show').andReturn(overlay);
var dialog = new Dialog(overlay);
dialog.show();
expect(overlay.show). toHaveBeenCalled();
于 2013-03-02T17:39:12.747 回答