我正在使用 Jest 为我的 React JS Web 应用程序编写单元测试/集成测试。我正在测试的组件正在异步进行 API 调用。我正在使用这个库https://github.com/ctimmerm/axios-mock-adapter来模拟 API 请求。
这是我的组件
import React, { useState, useEffect } from 'react';
import Axios from 'axios';
const ExampleList = (props) => {
const [ list, setList ] = useState([ ])
const fetchList = async () => {
let response = await Axios.get("http://dummy.restapiexample.com/api/v1/employees")
setList(response.data.data)
}
const renderList = () => {
return list.map((item, index) => {
return <li key={index}>{item.employee_name}</li>
})
}
useEffect(() => {
fetchList()
}, [ ])
return (
<div>
<ul>
{renderList()}
</ul>
</div>
)
}
export default ExampleList;
这是我模拟 API 请求的测试。
import React from 'react';
import {cleanup, fireEvent, render, screen, waitForElement} from '@testing-library/react';
import ExampleList from "../../src/components/ExampleList";
import MockAdapter from "axios-mock-adapter";
import Axios from 'axios';
test("ExampleList Component", async () => {
// first mock the API request.
let mock = new MockAdapter(Axios);
mock.onGet("http://dummy.restapiexample.com/api/v1/employees")
.reply(200, {
"status":"success",
"data":[
{
"id":"1",
"employee_name":"Wai Yan Hein",
"employee_salary":"720800",
"employee_age":"61"
}
]
})
let { getByText } = render(<ExampleList />)
const listData = await waitForElement(getByText("Wai Yan Hein"))
expect(listData).toBeTruthy()
})
当我运行测试时,我收到以下错误。
FAIL tests/unit/ExampleList.test.js
● Test suite failed to run
ReferenceError: regeneratorRuntime is not defined
5 | import Axios from 'axios';
6 |
> 7 | test("ExampleList Component", async () => {
| ^
8 | // first mock the API request.
9 | let mock = new MockAdapter(Axios);
10 | mock.onGet("http://dummy.restapiexample.com/api/v1/employees")
at Object.<anonymous> (tests/unit/ExampleList.test.js:7:5)
我的代码有什么问题,我该如何解决?