默认导出钩子时的模拟功能

时间:2020-05-07 17:59:04

标签: reactjs react-hooks

我有一个自定义钩子APIGateway,它调用了另一个自定义钩子http。我想模拟promise函数sendHttpRequest来测试sendAPIRequest。通过此代码,我得到“拒绝值:[TypeError:无法读取未定义的属性'then'”] 我试图避免任何__mock__文件。如果我模拟axios,则apiGateway.test通过。 如何在useHttp的默认导出上模拟sendHttpRequest函数?

http.js

import { useCallback } from 'react';
import axios from 'axios';

const useHttp = () => {
    const sendRequest = useCallback((url, method, body) => {
        return new Promise((resolve, reject) => {
            axios({ method: method, url: url, data: body, config: { crossDomain: true } })
                .then((response) => {
                    resolve(response.data);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }, []);

    return {
        sendHttpRequest: sendRequest,
    };
};

export default useHttp;

apiGateway.js

import { useCallback } from 'react';
import useHttp from '../abstract/http';
import configuration from '../../endpoints';

const useApiGateway = () => {
    const { sendHttpRequest } = useHttp();
    const apiGatewayBaseUrl = configuration.API_GATEWAY_BASE_URL;
    const apiGatewayPath = configuration.LAMBDA_USER_ENDPOINT;

    const sendRequest = useCallback((body) => {
        return new Promise((resolve, reject) => {
            sendHttpRequest(apiGatewayBaseUrl + apiGatewayPath, 'get', body)
                .then((response) => {
                    resolve(response);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }, []);

    return {
        sendApiRequest: sendRequest,
    };
};

export default useApiGateway;

apiGateway.test.js

import React from 'react';
import { act, renderHook } from '@testing-library/react-hooks';

import useApiGateway from './apiGateway';
import useHttp from '../abstract/http';
jest.mock('../abstract/http', () => jest.fn());
describe('hook/aws/apiGateway', () => {
    let result;
    beforeEach(() => {});

    it('should send GET request with no error', () => {
        //TODO mock http instead of axios
        let response = { data: '<html>Hello</html>' };
        useHttp.mockImplementation(() => ({
            sendHttpRequest: jest.fn(() => {}),
        }));
        let { sendHttpRequest } = useHttp();
        sendHttpRequest.mockResolvedValue(
            new Promise((resolve, reject) => {
                resolve(response);
            })
        );
        result = renderHook(() => useApiGateway()).result;
        console.log(useHttp());
        act(() => {
            return expect(result.current.sendApiRequest({})).resolves.toEqual(response.data);
        });
    });

});

完全错误

Error: expect(received).resolves.toEqual()

Received promise rejected instead of resolved
Rejected to value: [TypeError: Cannot read property 'then' of undefined]

    at expect (.../node_modules/expect/build/index.js:138:15)
    at .../apiGateway.test.js:29:11

1 个答案:

答案 0 :(得分:0)

您的模拟应返回一个promise(而不是尝试模拟promise lib)

示例:

function myMockRequest() {
    return Promise.resolve({ mockResponse });
}
相关问题