我对axios get的jest测试模拟返回了undefined
作为响应,我不确定我做错了什么?
我的组件具有axios调用,如下所示:
import {AgGridReact} from "ag-grid-react";
import React, {useEffect, useState, useMemo} from 'react';
useEffect(() => {
if(searchObject)
console.log("new being fetched")
fetchResults(gridApi);
}, [searchObject]);
const fetchResults = (paramsApi) => {
Service()
.getResults(searchObject)
.then((response) => {
console.log("calling.....", response); // undefined for response, why?
let results = response.data.results;
// more code below but unnecessary to show since response is undefined
字符串
Jest测试类:
import * as React from 'react';
import { screen } from '@testing-library/dom';
import { render } from '@testing-library/react';
import AgGridResults from "./AgGridResults";
describe('AgGridResults', () => {
beforeEach(async () => {
jest.mock("../../service/Service", () => ({
__esModule: true,
default: () => ({
getResults: async () => ({
data: { results: { M0: { value: ["Source ID"] } } },
}),
}),
}));
render(<AgGridResults searchObject={...} />);
await waitFor(() => expect(screen.getByText('Actions')).toBeInTheDocument())
});
test('AgGridResults', () => {
expect(screen.getByText('Actions')).toBeInTheDocument();
});
});
import axios from 'axios';
import UrlUtility from './urlUtility';
function Service() {
return {
getResults: async (searchObject) => {
let urlString = UrlUtility().convert(searchObject);
if (searchObject && urlString) {
return await axios.get('/api/' + urlString + '&pageLength=50');
}
},
getAgreementTypes: async (searchTerm) => {
return await axios.get('/api/' + 'searchString=' + searchTerm);
},
};
}
export default Service;
2条答案
按热度按时间pgvzfuti1#
当你的组件实际上并不使用Axios时,模仿Axios会产生一种脆弱的耦合。如果你改变了
Service
的实现,你的测试就会中断。我会在组件测试中模拟
Service
字符串
jfgube3f2#
试试这个
字符串
https://www.npmjs.com/package/axios-mock-adapter