javascript - 测试从回调中调用的 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");
});
});
解决方案
我这样解决了
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");
});
});
推荐阅读
- python-3.x - 如何使用 python 根据 Snowflake 中列的数据类型屏蔽特定模式中所有表的所有 PII 列?
- python - 如何在 Python Selenium 中与 Chrome 上的打印模式交互
- android - 在使用 kotlin 在 android 中验证电子邮件 ID 时,总是收到无效的电子邮件。我需要验证以 @univ.ac.in 结尾的邮件
- c - 将位间隔从变量复制到数组
- c - 对“checkResults”的未定义引用
- reactjs - DataCloneError:无法在“历史”上执行“pushState”:函数句柄用户发布(_x5,_x6)
- ruby-on-rails - `connects_to` 只能在 ActiveRecord::Base 或抽象类上调用
- ruby-on-rails - 当库存少于 5 时,如何删除 shopify 上的“立即购买”按钮(与 Rails 集成)
- smtp - .net 5框架下的Mailkit:SMTP服务器意外断开
- mongodb - 如何将 mongodb 与 Next js ISR / SSR 谷歌云功能 (firebase) 一起使用 增量静态再生 firebase nextjs