在Promise上启用假计时器并传递解析值

时间:2019-03-11 17:59:02

标签: javascript jestjs

我有一个模拟函数,可以伪造带有fetch的请求。我希望延迟调用此模拟函数,以检查是否触发了测试函数中的timeout属性。我目前这样延迟承诺:

   jest.useFakeTimers();

(request as jest.Mock).mockImplementationOnce(() =>
    Promise.resolve(response1).then(() => jest.advanceTimersByTime(3000))
);

在我测试的函数中,如果在config中设置了timeout属性,并且如果请求函数(我们在测试服中模拟的函数花费的时间更长,则超时)触发了setTimeOut,则将配置作为redux状态setTimeOut的cb应该被触发,失败/错误功能应该被触发)。这段代码看起来像这样:

` return new Promise((resolve: () => void) => {
            const timeout = config.timeout || globalConfig.timeout;
            let abortTimeout: any;
            let aborted = false;
            if (timeout) {
                abortTimeout = setTimeout(
                    () => {
                        const error = new Error('Timeout');
                        console.log(timeout);
                        dispatch(apiDataFail(requestKey, error));
                        onError(error);
                        aborted = true;
                    },
                    timeout`enter code here`
                );
            }
            requestFunction(formatUrl(config.url, params), requestProperties).then(
                ({ response, body: responseBody }: HandledResponse) => {
                    if (aborted) {
                        return;
                    }

测试看起来像这样:

test('The function resolves with a timeout argument', async (done) => {
    state = { apiData: getState('getData', true, {}, 'ready', 'GET', -1, undefined, undefined, 2900) };
    const resolves = await (performApiRequest('getData', {}, { data: 'json' })(dispatch, () => store.getState()))
    expect(resolves).toBeUndefined()
    const error = new Error('Timeout');
    const requestKey = getRequestKey('getData');
    expect(dispatch).toHaveBeenCalledWith(apiDataFail(requestKey, error));
    done();
});
  

超时已正确触发,但测试中出现错误:   TypeError:无法读取未定义的属性“响应”

0 个答案:

没有答案