【发布时间】:2018-02-22 13:37:44
【问题描述】:
我偶然发现了一个测试异步代码的问题。
这是我的函数的代码:
export default base64String =>
new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => {
const dimensions = {
width: image.width,
height: image.height,
};
resolve(dimensions);
};
image.onerror = err => reject(err);
image.src = base64String;
});
它接受一个base64编码的字符串并返回图像的宽度和高度;
测试如下:
import checkBase64 from '../src/helpers/check-base64';
import base64String from './base64String';
test('should return width and height of an image in base64', async () => {
const result = await checkBase64(base64String);
});
问题是测试失败并出现错误:
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
我关注了jest docs 和some stack overflow questions,但他们都没有帮助
【问题讨论】:
-
是因为您在附加
onload事件之前设置了src吗?由于您从编码字符串设置源,它可能会同步“加载”它,因此您的事件处理程序永远不会触发。 -
我在测试中看不到任何断言。 Jest 可能会出错,因为它期待一个断言,但没有完成一个断言。除非这就是 checkBase64 正在做的事情?
-
@JamesThorpe,我已经更新了我的代码(在我的编辑器和这里),但没有成功。我得到同样的错误
-
你能显示
checkBase64的来源吗? @IvanPrizov -
@kingdaro 我问题中的第一个代码块是
checkBase64。我正在使用默认导出
标签: javascript node.js jestjs