【发布时间】:2021-10-22 23:14:22
【问题描述】:
大家好,我对简单测试有疑问,我尝试测试在链接标签中有文本,在导航中有链接标签,但我看到错误符号不是函数,你能帮帮我吗?
我的测试代码:
const mockUseLocationValue = {
pathname: "",
search: '',
hash: '',
state: null
}
jest.mock('react-router', () => ({
...jest.requireActual("react-router") as {},
useLocation: jest.fn().mockImplementation(() => {
return mockUseLocationValue;
})
}));
test("should render the home page", () => {
render(<Header />);
const navbar = screen.getByTestId("navbar");
const link = screen.getByTestId("home-link");
expect(link.innerHTML).toMatch("Home page");
expect(navbar).toContainElement(link);
});
我的原始代码:
export const Header = ():JSX.Element => {
const location = useLocation()
const { pathname } = location
const splitLocation = pathname.split('/')
return (
<HeaderBlock as='h3' block>
<nav data-testid="navbar">
<ul className={styles.links}>
<li>
<Link data-testid="home-link" to="/">
Home Page
</Link>
</li>
</ul>
</nav>
</HeaderBlock>
)
}
【问题讨论】:
-
你为什么要模拟你要测试的代码? RTL 测试功能可以采用
wrapper选项...您应该使用它来将正在测试的组件包装在路由器组件中。 -
@DrewReese 我开始学习测试而不进行模拟我看到错误位置未定义你能告诉我如何修复错误吗
标签: reactjs typescript jestjs react-testing-library