开玩笑的nextjs:您应该只使用“ Next/Router”在您应用的客户端

发布于 2025-02-12 12:59:15 字数 750 浏览 0 评论 0原文

我正在嘲笑next/router在我的嘲笑+react-testing-libray测试中的依赖项,就像我往常一样:

import * as nextRouter from 'next/router';

export const routerData = {
  pathname: '/users/create',
  route: '/users/create',
  query: { },
  asPath: '/users/create',
  isFallback: false,
  basePath: '',
  isReady: true,
  isPreview: false,
  isLocaleDomain: false,
  events: {},
};

// mock router
jest.mock('next/router');
nextRouter.useRouter.mockImplementation(() => (routerData));

describe('a component that requires next/router, () => ... );

它已经正常工作,但是在更新到nextjs 12.2.0 我得到了此警告:

找不到路由器实例。 您只能在应用程序的客户端使用“ Next/Router”。

此警告使我所有的测试与嘲笑的路由器失败。

解决这个问题?

I'm mocking the next/router dependency in my Jest+React-testing-libray tests as I always have:

import * as nextRouter from 'next/router';

export const routerData = {
  pathname: '/users/create',
  route: '/users/create',
  query: { },
  asPath: '/users/create',
  isFallback: false,
  basePath: '',
  isReady: true,
  isPreview: false,
  isLocaleDomain: false,
  events: {},
};

// mock router
jest.mock('next/router');
nextRouter.useRouter.mockImplementation(() => (routerData));

describe('a component that requires next/router, () => ... );

This had been working correctly but after updating to NextJs 12.2.0 I get this warning:

No router instance found.
You should only use "next/router" on the client side of your app.

This warning makes all my tests with the mocked router to fail.

Ideas to fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女情怀诗 2025-02-19 12:59:15

好吧,看来这与12.2.0无关。不知何故,我的下一个版本的下一个 - 12.0.0 - 不是抛出此错误,但其他较旧版本也没有。

感谢 bistacos 响应

const useRouter = jest.spyOn(require('next/router'), 'useRouter');
useRouter.mockImplementation(() => ({
  pathname: '/',
  ...moreRouterData
}));

Well, it appears that this is not related to 12.2.0. Somehow my last version of Next - 12.0.0 - wasn't thrownig this error but other older versions did.

Thanks to bistacos for the response here.

const useRouter = jest.spyOn(require('next/router'), 'useRouter');
useRouter.mockImplementation(() => ({
  pathname: '/',
  ...moreRouterData
}));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文