如何动态模拟组件?

发布于 2025-02-11 13:37:28 字数 817 浏览 1 评论 0原文

我正在使用Jest和Testing-Library。

我必须模拟我要测试的组件的每个子组件,就像这样做的那样:

jest.mock('react-router-dom', () => ({
  NavLink: (props: any) => {
    const NavLinkMock = 'NavLink-Mock';
    // @ts-ignore
    return <NavLinkMock {...props} />;
  },
}));

但是,由于我不想在应用程序上复制粘贴指令,所以我编写了一个函数以模拟任何组件:

export function mockComponent(source: string, name: string) {
  jest.mock(source, () => ({
    [name]: (props: any) => {
      const ComponentMock = `${name}-mock`;
      // @ts-ignore
      return <ComponentMock {...props} />;
    },
  }));
}

运行测试时,我遇到了这个错误:

> The module factory of `jest.mock()` is not allowed to reference any
> out-of-scope variables.
>     Invalid variable access: name

任何人可以保存一天吗?

I'm using jest with testing-library.

I have to mock every child component of the component I want to test, like this which works fine :

jest.mock('react-router-dom', () => ({
  NavLink: (props: any) => {
    const NavLinkMock = 'NavLink-Mock';
    // @ts-ignore
    return <NavLinkMock {...props} />;
  },
}));

But because I dont want to copy paste the mocking instructions all over the app, I wrotre a function to mock any component :

export function mockComponent(source: string, name: string) {
  jest.mock(source, () => ({
    [name]: (props: any) => {
      const ComponentMock = `${name}-mock`;
      // @ts-ignore
      return <ComponentMock {...props} />;
    },
  }));
}

When running the test, I get this error :

> The module factory of `jest.mock()` is not allowed to reference any
> out-of-scope variables.
>     Invalid variable access: name

Can anyone save the day ?

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

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

发布评论

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

评论(1

我也只是我 2025-02-18 13:37:28

您需要在变量中以“模拟”为前缀模拟的组件。这是针对非初始化的模拟变量的预防措施,允许使用模拟的变量名称。

You need to prefix mocked component in a variable with "mock". It is a precaution against uninitialized mock variables, variable names prefixed with mock are permitted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文