[英]Why does using MUI React components as child components produce errors during testing?
我有一个父组件 Navbar,它有几个 MUI React 子组件。 当我使用测试库的渲染 function 测试 Navbar 组件时,它会产生以下错误:
错误:未捕获 [错误:元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件)但得到:object。
检查
Navbar
的渲染方法。
但是,如果我从 Navbar 中删除 MUI React 组件,它就不会再产生错误。 如何解决这个问题?
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>
);
};
删除并解决问题,因为它们都是 MUI 组件。
尝试使用简单的代码块导入 MUI 组件。 看起来工作正常。
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);
});
结果:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.