测试是否执行了从回调调用的window.open



我有一个类似的函数:

openUrl(): void {
const url: string = "http://www.xpto.com";
this.MyService.load(url).then( response => {
const file = new Blob([response]);
if (file.size > 0) {
window.open(url,"_blank");
}
});
}

如何创建一个测试来验证window.open是否使用URL调用?

我开始创建下面的代码,但我不知道如何模拟回调。

describe("Button for download", () => {
it("should open the correct URL", () => {
// given

// when
underTest.openUrl();
// then
expect(window.open).toHaveBeenCalledWith("http://www.xpto.com");
});
});

我用这种方法解决了

describe("Button for download", () => {
it("should open the correct URL", () => {
// given
spyOn(window, "open");
spyOn(MyService, "load").and.returnValue($q.resolve(["content"]));
// when
underTest.openUrl();
// then
expect(MyService.load).toHaveBeenCalled();
$rootScope.$apply();
expect(window.open).toHaveBeenCalledWith("http://www.xpto.com", "_blank");
});
});

最新更新