我试图通过模拟用于从外部API获取数据的函数来测试react组件,该函数是从useEffect钩子中调用的。但是我得到以下错误Cannot read properties of undefined (reading 'then') TypeError: Cannot read properties of undefined (reading 'then')
我已经尝试过用useEffect将函数定义从中分离出来,以提高可测试性,但也可以使用一些指针。
根据建议,我尝试将数据获取和组件分离,以提高可测试性。
数据获取和测试组件的示例如下所示:
数据提取的定义为:
// api.ts
import {EmployeeModel} from "../models/EmployeeModel";
export async function getAllEmployees(): Promise<EmployeeModel[]> {
const baseUrl: string = "http://localhost:8080/employees";
const response: Response = await fetch(baseUrl);
const responseJson = await response.json();
const employees: EmployeeModel[] = [];
for (let key in responseJson) {
const emp: EmployeeModel = new EmployeeModel(
responseJson[key].name,
responseJson[key].gender,
responseJson[key].address,
responseJson[key].postcode,
responseJson[key].department,
responseJson[key].salary,
responseJson[key].email,
responseJson[key].employeeNumber
);
employees.push(emp);
}
return employees;
}
测试的组件:
// React component
import React, {useEffect, useState} from "react";
import {JSX} from "react";
import {EmployeeTable} from "./EmployeeTable";
import {EmployeeModel} from "../models/EmployeeModel";
import {getAllEmployees} from "../services/EmployeeApiService";
import {Simulate} from "react-dom/test-utils";
import {EmployeeDataTransferModel} from "../models/EmployeeDataTransferModel";
export const EmployeeTableWrapper: React.FC<{}> = (props): JSX.Element => {
const [employees, setEmployees] = useState<EmployeeModel[]>([]);
useEffect((): void => {
getAllEmployees()
.then((response: EmployeeModel[]): void => {
setEmployees(response)
})
.catch((error: any) => {
});
// setIsLoading(false);
}, [getAllEmployees])
return (
<EmployeeTable employees={employees}/>
)
}
和所创建的测试:
Finally the test that has been written so far (I have removed the asserts until the I can get the test passing):
`import React from 'react';
import {render, screen} from '@testing-library/react';
import {EmployeeTableWrapper} from "../../components/EmployeeTableWrapper";
import {getAllEmployees} from "../../services/EmployeeApiService";
import {EmployeeModel} from "../../models/EmployeeModel";
const mockEmployees: EmployeeModel[] = [
new EmployeeModel(
"Test_User",
"M",
"3 Fake Street",
"M1",
5,
"Tech",
23000.0,
"test2test.com")
]
jest.mock("../../services/EmployeeApiService", () => ({
getAllEmployees: jest.fn(() => Promise.resolve(mockEmployees))
}));
describe("EmployeeTableWrapper", () => {
it('should ', async function () {
await act(async() => {
render(<EmployeeTableWrapper />)
await getAllEmployees();
})
});
});`
任何建议将不胜感激。
1条答案
按热度按时间xtfmy6hx1#
看起来你刚刚做了错误的Just.mock为getAllEmployees。它在测试之外,因此在测试中不可见。将其移至测试并再次检查测试: