繁体   English   中英

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

[英]Async test in Jest failing due to unresolved promise

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

在他们的文档中,有这样的:“如果一个promise根本没有解决,可能会抛出此错误: - 错误:超时 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL.指定的超时内没有调用异步回调jasmine.DEFAULT_TIMEOUT_INTERVAL.最常见的是这是由冲突的Promise实现。考虑用您自己的实现替换全局promise实现,例如global.Promise = require.requireActual('promise');和/或将使用过的Promise库合并为一个。“

这可能是问题所在,但我不清楚如何解决我的问题或确定Promise的破坏位置。

也许我对Jest中的模拟的理解是错误的? 我尝试使用他们的例子,当然它工作得很好。 https://facebook.github.io/jest/docs/tutorial-async.html#content

这是我在控制台中得到的:

● 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');

我的要求不正确,承诺永远不会回来。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM