如何使用Jest测试img.onload? [英] How to test img.onload using Jest?

查看:387
本文介绍了如何使用Jest测试img.onload?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持使用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.

以前访问过:

  • How do you use Jest to test img.onerror
  • How to test asnyc code with Jest ( or test "image.onload" with jsdom )
  • How do I test `image.onload` using jest in the context of redux actions (or other callbacks assigned in the action)

要测试的代码:

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

我也收到一个错误:

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆