这是我要测试的反应类。我正在使用Content.Provider
以保持全局状态。在我的测试文件中,我将其命名为<Store>
.
import { useEffect, useContext } from "react";
import { Context } from '../../config/Store';
const ProjectPage = () => {
const [globalState, dispatch] = useContext(Context);
useEffect(() => {
getAllProjectData();
}, []);
const getAllProjectData = async () => {
console.log('### getAllProjectData - ProjectPage.jsx')
try {
const data = await getProjectData();
dispatch({ type: 'setIsLoaded', payload: true })
dispatch({ type: 'setError', payload: false })
dispatch({ type: 'setProjectDetails', payload: data })
} catch (error) {
console.log("### Error: ", error)
dispatch({ type: 'setProjectDetails', payload: null })
dispatch({ type: 'setIsLoaded', payload: true })
dispatch({ type: 'setError', payload: true })
}
}
if (globalState.error) {
return <div><ErrorPage /></div>;
} else if (!globalState.isLoaded) {
return <div className="spinnerContainer" data-testid="spinnerContainer"
<CircularProgress className="spinner" color="error" size="3rem" thickness={7} />
</div>;
} else {
return <div id="projectToolbar" data-testid="projectTabBar" className="container-fluid"></div>;
}
}
export default ProjectPage;
然后我有这个test.js
文件,其中第一个测试成功,第二个测试失败。
import Store from '../../config/Store';
import ProjectPage from './ProjectPage';
import { render } from '@testing-library/react';
test('renders the spinner before the project page', () => {
const { getByTestId } = render(<Store><ProjectPage /></Store>);
const spinnerContainer = getByTestId("spinnerContainer");
expect(spinnerContainer).toBeInTheDocument();
});
test.only('renders the project tab bar', async () => {
render(<Store><ProjectPage /></Store>);
const projectTabBar = await waitFor(async () => await screen.findByTestId("projectTabBar"))
expect(projectTabBar).toBeInTheDocument();
});
在我的记录器中,测试显示以下内容:
如您所见,测试失败,因为data-testid="projectTabBar"
不在文档中并且微调器在那里。我知道发生这种情况是因为组件没有呈现数据,但我不明白为什么会发生这种情况以及如何解决它。任何帮助,将不胜感激。