React Jest:如何模拟返回数据的异步 API 调用?
Posted
技术标签:
【中文标题】React Jest:如何模拟返回数据的异步 API 调用?【英文标题】:React Jest: How do I mock an async API call that returns data? 【发布时间】:2021-01-10 16:02:25 【问题描述】:我正在尝试测试一个 React 表组件(它使用异步 API 调用来返回表数据),但无法弄清楚如何模拟 API 调用以满足我的 React 测试文件。我有一个模拟数据文件来提供模拟数据。 (我只包含了相关代码)。
模拟数据:
const mockRequestData = [
"email": "runner1@test.com",
"firstName": "runner1",
"lastName": "runner1"
,
"email": "runner2@test.com",
"firstName": "runner2",
"lastName": "runner2"
,
"email": "runner3@test.com",
"firstName": "runner3",
"lastName": "runner3"
,
];
export const mockData =
mockData: mockRequestData,
;
apiCall 在自己的文件中:
const getAllAthletesSigningUp = async () =>
let athletesSigningUp= [];
const response = await returnGetResponse("/api/atheletesignup");
if (response.status === 200)
return athletesSigningUp= (response.body);
return athletesSigningUp
;
export getAllAthletesSigningUp;
runnerTable 应用:
const [requests, setRequests] = useState([]);
useEffect( () =>
apiResponse();
,[]);
const apiResponse = async () =>
return setRequests(await getAllAthletesSigningUp ())
<div className="table_content">
requests.map((request, index) =>
return (
<>
<div key=index className="table_row" data-testid="tableRow">
<p>formatText(request.email)</p>
<p>formatText(request.firstName)</p>
<p>formatText(request.lastName)</p>
【问题讨论】:
【参考方案1】:你可以使用jest.mock()
:
jest.mock(<path to getAllAthletesSigningUp>, () => (
getAllAthletesSigningUp: jest.fn(() => [<mock data>])
))
describe('...', () =>
it('...', () =>
// const getAllAthletesSigningUp = jest.requireMock(<path>) - if You need mocked implementation in test;
// const getAllAthletesSigningUp = jest.requireActual(<path>) - if You need original implementation in test;
)
)
或在单个测试中直接使用mockImplementation
或mockImplementationOnce()
描述实现:
jest.mock(<path to getAllAthletesSigningUp>, () => (
getAllAthletesSigningUp: jest.fn()
))
describe('...', () =>
it('...', () =>
const getAllAthletesSigningUp = jest.requireMock(<path>)
// getAllAthletesSigningUp.mockImplementation(() => [<mock data>]) - for all function calls;
// getAllAthletesSigningUp.mockImplementationOnce(() => [<mock data>]) - for single function call;
)
)
【讨论】:
我尝试了您的第二个选项,但我收到此错误:属性 'mockImplementationOnce' 在类型 '() => Promise' 上不存在。以上是关于React Jest:如何模拟返回数据的异步 API 调用?的主要内容,如果未能解决你的问题,请参考以下文章
Jest / Enzyme - 生命周期方法中的模拟异步函数
如何使用 Jest 在本机反应中模拟“react-native-config”库的配置数据?