我偶然发现了测试异步代码的问题。
这是我的功能代码:
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,但他们都没有帮助
答案 0 :(得分:2)
Image
构造函数仅存在于DOM中,Jest测试在Node中运行。看起来checkBase64函数返回的promise在尝试访问Image
时无声地失败。您需要使用最小化(global.Image = ...
)或像jsdom这样功能齐全的内容来模拟它。