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

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

Cant read router when testing in nextjs

问题

这是我的测试代码:

  1. const buttonElement = screen.getByTestId('footerButton');
  2. expect(buttonElement).toBeInTheDocument();
  3. userEvent.click(buttonElement);
  4. expect(window.location.href).toBe('http://localhost/');

这是该组件:

  1. <button
  2. className={styles.footerButtonPC}
  3. data-testid="footerButtonPC"
  4. onClick={() => router.push('/')}
  5. >
  6. 完整的尺码指南
  7. </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:

  1. Cannot read properties of null (reading &#39;push&#39;)
  2. 71 | className={styles.footerButton}
  3. 72 | data-testid=&quot;footerButton&quot;
  4. &gt; 73 | onClick={() =&gt; router.push(&#39;/&#39;)}
  5. |

This is my test code:

  1. const buttonElement = screen.getByTestId(&#39;footerButton&#39;);
  2. expect(buttonElement).toBeInTheDocument();
  3. userEvent.click(buttonElement);
  4. expect(window.location.href).toBe(&#39;http://localhost/&#39;);
  5. ^

This is the component:

  1. &lt;button
  2. className={styles.footerButtonPC}
  3. data-testid=&quot;footerButtonPC&quot;
  4. onClick={() =&gt; router.push(&#39;/&#39;)}
  5. &gt;
  6. Full Fit &amp; Size Guide
  7. &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"

  1. import mockRouter from "next-router-mock";
  2. jest.mock("next/router", () => require("next-router-mock"));

然后,在测试中,你可以按以下方式使用它:

  1. mockRouter.push("/your-initial-url"); // 可选
  2. mockRouter.push = jest.fn();
  3. // 行为
  4. 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"

  1. import mockRouter from &quot;next-router-mock&quot;;
  2. 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:

  1. mockRouter.push(&quot;/your-initial-url&quot;); // Optionally
  2. mockRouter.push = jest.fn();
  3. // Act
  4. 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:

确定