【问题标题】:Problems testing async function测试异步功能的问题
【发布时间】: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 docssome stack overflow questions,但他们都没有帮助

【问题讨论】:

  • 是因为您在附加onload 事件之前设置了src 吗?由于您从编码字符串设置源,它可能会同步“加载”它,因此您的事件处理程序永远不会触发。
  • 我在测试中看不到任何断言。 Jest 可能会出错,因为它期待一个断言,但没有完成一个断言。除非这就是 checkBase64 正在做的事情?
  • @JamesThorpe,我已经更新了我的代码(在我的编辑器和这里),但没有成功。我得到同样的错误
  • 你能显示checkBase64的来源吗? @IvanPrizov
  • @kingdaro 我问题中的第一个代码块是checkBase64。我正在使用默认导出

标签: javascript node.js jestjs


【解决方案1】:

Image 构造函数只存在于 DOM 中,Jest 测试在 Node.js 中运行。看起来从 checkBase64 函数返回的承诺在尝试访问 Image 时静默失败。你需要模拟它,或者用最小的东西 (global.Image = ...) 或者像 jsdom 这样的功能齐全的东西。

【讨论】:

  • 我已经尝试了您的两个建议,但都没有帮助。当我尝试使用expect.assertions(2) 时,出现错误Expected two assertions to be called but received zero assertion calls。顺便说一句,没有expectdone 的笑话测试工作正常。他们只是通过了
  • 我用一个应该如何使用 expect.assertions 的例子来编辑我的答案。您给我的错误消息告诉我 checkBase64 函数实际上可能无法解析。如果你console.log(result) 会发生什么?
  • 另外...不要开玩笑测试在节点中运行?节点中不存在图像。如果那是的问题,我会重写我的答案。
  • 噢...我想这就是问题所在。我的意思是,我真的不知道节点中不存在image
  • 我明白了。那么,我怀疑诺言正在悄然失败。编辑我的答案
猜你喜欢
  • 1970-01-01
  • 2013-10-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
相关资源
最近更新 更多