由于未解决的承诺,Jest中的异步测试失败

Async test in Jest failing due to unresolved promise

本文关键字:异步 测试 失败 Jest 未解决 承诺      更新时间:2023-09-26

我正在学习Jest并遇到一个问题,试图模拟返回fetch承诺的异步函数。

在他们的文档中,有这样的:如果promise没有解决,则可能会抛出以下错误:—Error: Timeout—未在jasmine.DEFAULT_TIMEOUT_INTERVAL.指定的超时时间内调用异步回调最常见的原因是承诺实现冲突。考虑用自己的实现取代全局承诺,例如global.Promise = require.requireActual('promise');和/或将使用的承诺库合并为一个。"

这可能是问题,但我不清楚如何解决我的问题或确定Promise在哪里打破。

也许我对嘲笑的理解是错误的?我试着用他们的例子,当然效果很好。(https://facebook.github.io/jest/docs/tutorial-async.html内容)

这是我在控制台得到的结果:

● endpoint can receive form data › can parse and fulfill a promise
    Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

下面是我的模块和测试:

// myModule/index.js
import { OK } from 'http-status-codes';
import request from './request';
import parseForm from '../../../../modules/parseMultiPart';
export default (req, res, next) => parseForm(req)
    .then(body => request(body, req)
    .then(result => result.text())
    .then(result => res.status(OK).send(result)))
.catch(next);

// myModule/request.js
import fetch from 'node-fetch';
export default (body, req) => fetch('http://url', {
    method: 'POST',
    body: JSON.stringify(body.fields),
    headers: {
        'Content-Type': 'application/json',
        'X-Request-Id': req.id
    }
});

// myModule/__tests__/myModule.test.js
import MockReq from 'mock-req';
import MockRes from 'mock-res';
import myModule from '../';
jest.mock('../request');
describe('endpoint can receive form data', () => {
    const response = new MockRes();
    const request = new MockReq({
        method: 'POST',
        url: '/webhook',
        headers: {
            'Content-Disposition': 'form-data; name="file"; filename="plain.txt"',
            'Content-Type': 'multipart/form-data; custom=stuff; boundary=----TLV0SrKD4z1TRxRhAPUvZ',
            'Content-Length': 213
        }
    });
    it('can parse and fulfill a promise', () => myModule(request, response)
        .then(text => expect(text).toEqual('API Event Received'))
    );
});

// myModule/__mocks__/request.js
export default function request() {
    return new Promise((resolve) => {
        process.nextTick(
            () => resolve('API Event Received')
        );
    });
}

我嘲笑错了。在本例中需要模拟函数,而不是数据:

jest.mock('../parseMultiPart');
jest.mock('../request');

我的请求不正确,承诺永远不会返回。