首页 > 解决方案 > 测试从回调中调用的 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");
    }
  });
}

如何创建测试以验证是否使用 URL 调用了 window.open?

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

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

      // when
      underTest.openUrl();

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

标签: javascriptunit-testingjasmine

解决方案


我这样解决了

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");
        });
    });

推荐阅读