This is the react class that I want to test.
I am using Content.Provider
in order to keep a global state.
In my testing file, I name it <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;
Then I have this test.js
file in which the first test succeeds and the second fails.
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();
});
In my logger the test shows the following:
As you can see the test fails because data-testid="projectTabBar"
is not in the document and the spinner is there. I understand that this is happening because the component doesn't render the data but I don't understand why is this happening and how to resolve it. Any help would be appreciated.