2016-11-11 42 views
1

我正在学习Jest并运行到试图模拟异步函数的问题,该异步函数返回fetch的承诺。由于未解决的承诺导致Jest失败的异步测试

在他们的文档,还有这个: “如果一个承诺不能解决所有,可能会抛出这个错误: - 错误:超时 - 异步回调不被jasmine.DEFAULT_TIMEOUT_INTERVAL. 最常见的是这个规定的超时时间内调用是由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') 
     ); 
    }); 
} 

回答

0

我在嘲笑错误的事情。需要被嘲讽的功能,而不是数据在这种情况下:

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

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

相关问题