如何动态模拟组件?
我正在使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在变量中以“模拟”为前缀模拟的组件。这是针对非初始化的模拟变量的预防措施,允许使用模拟的变量名称。
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.