Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

javascript - 如何使用Jest测试img.onload?(How to test img.onload using Jest?)

I'm stuck with img.onload event testing.

(我陷入img.onload事件测试。)

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.

(我也看到过一些类似的案例,但它们与本案例有所不同。)

Previously visited:

(以前访问过:)

Code to test:

(要测试的代码:)

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

Testing environment:

(测试环境:)

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 => {...

Thanks in advance!

(提前致谢!)

  ask by Max Travis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is my solution:

(这是我的解决方案:)

index.ts :

(index.ts :)

function funcToTest(imgUrl, callback) {
  const img = new Image();
  img.src = imgUrl;

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

  return img;
}

export { funcToTest };

Unit test:

(单元测试:)

/**
 * @jest-environment jsdom
 */

import { funcToTest } from './';

describe('test suites', () => {
  it('onload', done => {
    const callback = jest.fn(status => {
      expect(status).toBe(true);
      done();
    });

    const imageUrl = 'https://github.com/mrdulin';
    const img = funcToTest(imageUrl, callback);
    if (img.onload) {
      const event: any = {};
      img.onload(event);
    }
  });

  it('onerror', done => {
    const consoleLogSpyOn = jest.spyOn(console, 'log');
    const callback = jest.fn(status => {
      expect(status).toBe(false);
      done();
    });

    const imageUrl = 'https://github.com/mrdulin';
    const img = funcToTest(imageUrl, callback);
    if (img.onerror) {
      const event: any = { message: 'some error' };
      img.onerror(event);
      expect(consoleLogSpyOn).toBeCalledWith(event);
    }
    consoleLogSpyOn.mockRestore();
  });
});

Unit test result and coverage:

(单元测试结果和覆盖范围:)

 PASS  src/stackoverflow/57092154/index.spec.ts
  test suites
    ? onload (8ms)
    ? onerror (8ms)

  console.log node_modules/jest-mock/build/index.js:860
    { message: 'some error' }

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.821s

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57092154

(这是完整的演示: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57092154)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...