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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With