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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…