无法在 Next.js 中进行路由器测试时读取。

huangapple go评论65阅读模式
英文:

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 &#39;push&#39;)

      71 |                         className={styles.footerButton}
      72 |                         data-testid=&quot;footerButton&quot;
    &gt; 73 |                         onClick={() =&gt; router.push(&#39;/&#39;)}
         |     

This is my test code:

const buttonElement = screen.getByTestId(&#39;footerButton&#39;);
      expect(buttonElement).toBeInTheDocument();
      userEvent.click(buttonElement);

      expect(window.location.href).toBe(&#39;http://localhost/&#39;);
                                      ^

This is the component:

&lt;button
                        className={styles.footerButtonPC}
                        data-testid=&quot;footerButtonPC&quot;
                        onClick={() =&gt; router.push(&#39;/&#39;)}
                      &gt;
                        Full Fit &amp; Size Guide
                      &lt;/button&gt;

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 &quot;next-router-mock&quot;;
jest.mock(&quot;next/router&quot;, () =&gt; require(&quot;next-router-mock&quot;));

Then, in tests, you'll be able to use it in the following ways:

mockRouter.push(&quot;/your-initial-url&quot;); // Optionally
mockRouter.push = jest.fn(); 

// Act

expect(mockRouter.push).toHaveBeenCalledWith(&quot;http://localhost/&quot;);

huangapple
  • 本文由 发表于 2023年3月7日 18:04:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定