如何使用 Jest 测试 img.onload? [英] How to test img.onload using Jest?
问题描述
我一直在使用 img.onload
事件测试.我知道这是一个异步操作,它应该被嘲笑,但我仍然无法弄清楚如何解决这个问题.我也看到过几个类似的案例,但与本次不同.
I'm stuck with img.onload
event testing. I know that this is an async operation and it should be maybe mocked, but I still couldn't figure out how to solve the problem. I've also seen a couple of similar cases, but they are different from this one.
以前访问过:
- 如何使用Jest测试img.onerror
- 如何测试使用 Jest 的 asnyc 代码(或使用 jsdom 测试image.onload")
- 如何在 redux 动作(或动作中分配的其他回调)的上下文中使用 jest 测试 `image.onload`
要测试的代码:
function funcToTest(img, callback) {
const img = new Image()
img.src = img
img.onload = () => {
callback(true) // should return callback with true on finish
}
img.onerror = (e) => {
callback(false) // should return callback with false on error
console.log(e)
}
}
funcToTest()
测试环境:
describe('tet it', () => {
it('test', done => {
const callback = status => {
expect(status).toEqual(true) // but nothing happen
done()
}
funcToTest('some_image', callback)
})
})
我在结束时也遇到错误:
Also I get an error on the finish:
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
> 2 | it('test', done => {...
提前致谢!
推荐答案
虽然有人回答了这个问题,但我不同意解决方案的目的.
While this was answered, I disagree with the purpose of the solution.
我们不应该编写测试来通过覆盖率,我们应该编写测试来证明一个观点,并确保代码片段按预期运行.
We shouldn't write tests to pass coverage, we should write tests that prove a point, and ensure pieces of code behave as expected.
测试它的方法是模拟 Image 构造函数并将其替换为将调用 onload
函数的内容.
The way to test it is to mock the Image constructor and replace it with something that will invoke the onload
function.
describe('tet it', () => {
it('test', done => {
global.Image = class {
constructor() {
setTimeout(() => {
this.onload(); // simulate success
}, 100);
}
}
const callback = status => {
done()
}
funcToTest('some_image', callback)
})
})
该方法仅假设浏览器"将在 100 毫秒内下载图像,如果您需要在两者之间共享此行为,您可以调整失败的代码,或将其部分移动到 beforeEach
测试.
The method just assumes that the 'browser' will download the image within 100 ms, you can tweak the code for failure, or move parts of it to beforeEach
if you need to share this behavior between tests.
这篇关于如何使用 Jest 测试 img.onload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!