I have a parent component Navbar which have several MUI React child components. When I test the Navbar component with testing-library's render function it produces following error:
Error: Uncaught [Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of
Navbar
.
However, if I remove MUI React components from the Navbar, it doesn't produce the error anymore. How to fix this problem?
it('Should render all links', () => {
const { getAllByRole } = render(
<Router>
<Navbar username="test username" logout={vi.fn()} />
</Router>
);
const links = getAllByRole('link');
expect(links[0]).toHaveTextContent(/ResourcePlanning/i);
expect(links[1]).toHaveTextContent(/MobileView/i);
});
export const Navbar = ({ username, logout }) => {
const getTranslations = async () => {
// todo
window.location.reload();
};
return (
<StyledNav>
<StyleHeaderContainerDiv>
<StyledHeaderSpan>Title</StyledHeaderSpan>
</StyleHeaderContainerDiv>
<StyledHeaderLinksContainer>
<StyledLinkList>
<StyledLink to="/">ResourcePlanning</StyledLink>
<StyledLink to="/mobileview">MobileView</StyledLink>
</StyledLinkList>
</StyledHeaderLinksContainer>
<StyleHeaderContainerDiv>
<Icon path={mdiWeb} size={1.2} />
<TranslationButton type="button" onClick={() => getTranslations()}>
Get Translations
</TranslationButton>
</StyleHeaderContainerDiv>
<StyleHeaderContainerDiv>
<Button
variant="outlined"
style={{
color: 'white',
backgroundColor: '#555',
textAlign: 'center',
fontSize: '10px',
opacity: 0.9,
}}
onClick={() => logout()}
startIcon={<Icon path={mdiLogout} size={1.2} style={{ opacity: 1 }} />}
>
{username}
</Button>
</StyleHeaderContainerDiv>
</StyledNav>
);
};
Removing and solves the problems as both are MUI components.
Tried with simple block of code importing MUI components. It seems working fine.
import { Container, Link } from "@mui/material";
export const Navbar = ({ username, logout }) => {
return (
<div>
<div>
<span>Title</span>
</div>
<Container>
<Link to="/" data-testid={"link"}>
ResourcePlanning
</Link>
<Link to="/mobileview" data-testid={"link"}>
MobileView
</Link>
</Container>
</div>
);
};
NavBar.test.js
import { render } from "@testing-library/react";
import { Navbar } from "./NavBar";
it("Should render all links", () => {
const { getAllByTestId } = render(
<Navbar username="test username" logout={jest.fn()} />
);
const links = getAllByTestId("link");
expect(links[0]).toHaveTextContent(/ResourcePlanning/i);
expect(links[1]).toHaveTextContent(/MobileView/i);
});
Result:
PASS src/components/NavBar.test.js
✓ Should render all links (64 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.089 s
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.