У меня есть собственный перехватчик APIGateway, вызывающий другой настраиваемый перехватчик http. Я бы хотел поиздеваться над функцией обещания sendHttpRequest, чтобы протестировать sendAPIRequest. С помощью этого кода я получаю сообщение «Rejected to value: [TypeError: Cannot read property 'then' of undefined]» Я пытаюсь избежать любых файлов __mock__. Если я издеваюсь над ax ios, apiGateway.test проходит. Как я могу имитировать функцию sendHttpRequest при экспорте useHttp по умолчанию?
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. тест. 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