如何在Jasmine中测试JavaScript图像onerror回调?
我有一个url加载程序,可以传入url,它将使用动态创建的JavaScript如何在Jasmine中测试JavaScript图像onerror回调?,javascript,image,unit-testing,jasmine,Javascript,Image,Unit Testing,Jasmine,我有一个url加载程序,可以传入url,它将使用动态创建的JavaScriptnew Image()及其src属性加载url。如果发生错误,我会将其记录到控制台 简化的JavaScript代码将是: var UrlLoader = function(url) { this.url = url; this.image = new Image(); this.image.onerror = function() { console.log("image error"); }
new Image()
及其src
属性加载url。如果发生错误,我会将其记录到控制台
简化的JavaScript代码将是:
var UrlLoader = function(url) {
this.url = url;
this.image = new Image();
this.image.onerror = function() {
console.log("image error");
};
this.load = function() {
this.image.src = this.url;
};
}
我现在的问题是,如何在运行时测试执行了console.log(“图像错误”)
var urlLoader = new UrlLoader();
urlLoader.load("any.png");
我创建了一个,但没有通过规范,如果您能帮助我找到一种方法来测试
urloader
这是您用来检查是否调用了log方法的一行,我将不胜感激
expect(console.log).toHaveBeenCalledWith("image error");
这是正确的,但问题是到目前为止,onerror
处理程序尚未调用,因为要触发/处理的错误事件不是立即的,而是稍后异步的
您应该将测试用例更改为此
describe("A suite", function() {
beforeEach(function(done){
spyOn(console, "log");
var imageLoader = new ImageLoader("any.png");
imageLoader.image.addEventListener("error", function() {
done();
});
imageLoader.load();
});
it("contains spec with an expectation", function() {
expect(console.log).toHaveBeenCalledWith("image error");
});
});
您可以在中找到有关使用Jasmine测试异步代码的更多信息,这是您用来检查是否调用了log方法的行
expect(console.log).toHaveBeenCalledWith("image error");
这是正确的,但问题是到目前为止,onerror
处理程序尚未调用,因为要触发/处理的错误事件不是立即的,而是稍后异步的
您应该将测试用例更改为此
describe("A suite", function() {
beforeEach(function(done){
spyOn(console, "log");
var imageLoader = new ImageLoader("any.png");
imageLoader.image.addEventListener("error", function() {
done();
});
imageLoader.load();
});
it("contains spec with an expectation", function() {
expect(console.log).toHaveBeenCalledWith("image error");
});
});
您可以在中找到有关使用Jasmine测试异步代码的更多信息。感谢您提供了解决方案,并提供了有关其工作原理的解释链接。非常感谢。感谢您提供的解决方案以及有关其工作原理的解释链接。非常感谢。