Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock components dynamically?

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 ?

like image 887
Teehbow Avatar asked Mar 15 '26 08:03

Teehbow


1 Answers

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.

like image 126
The Average Google User Avatar answered Mar 16 '26 22:03

The Average Google User