英文:
Cant read router when testing in nextjs
问题
这是我的测试代码:
const buttonElement = screen.getByTestId('footerButton');
expect(buttonElement).toBeInTheDocument();
userEvent.click(buttonElement);
expect(window.location.href).toBe('http://localhost/');
这是该组件:
<button
className={styles.footerButtonPC}
data-testid="footerButtonPC"
onClick={() => router.push('/')}
>
完整的尺码指南
</button>
英文:
Hi what I am trying to do is test when button is pressed it redirects to '/'. Regulary it works but when I try to test it it fails giving me this:
Cannot read properties of null (reading 'push')
71 | className={styles.footerButton}
72 | data-testid="footerButton"
> 73 | onClick={() => router.push('/')}
|
This is my test code:
const buttonElement = screen.getByTestId('footerButton');
expect(buttonElement).toBeInTheDocument();
userEvent.click(buttonElement);
expect(window.location.href).toBe('http://localhost/');
^
This is the component:
<button
className={styles.footerButtonPC}
data-testid="footerButtonPC"
onClick={() => router.push('/')}
>
Full Fit & Size Guide
</button>
Im fairly new to react and testing in react in general so any help would be great. Thanks in advance
答案1
得分: 1
也许,你想要模拟路由器,因为它在服务器上下文中不可用。
考虑尝试 "next-router-mock"
import mockRouter from "next-router-mock";
jest.mock("next/router", () => require("next-router-mock"));
然后,在测试中,你可以按以下方式使用它:
mockRouter.push("/your-initial-url"); // 可选
mockRouter.push = jest.fn();
// 行为
expect(mockRouter.push).toHaveBeenCalledWith("http://localhost/");
英文:
Probably, what you want is to mock the router, because it's not available in the server context.
Consider trying "next-router-mock"
import mockRouter from "next-router-mock";
jest.mock("next/router", () => require("next-router-mock"));
Then, in tests, you'll be able to use it in the following ways:
mockRouter.push("/your-initial-url"); // Optionally
mockRouter.push = jest.fn();
// Act
expect(mockRouter.push).toHaveBeenCalledWith("http://localhost/");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论