Reactjs 在使用Jest进行测试时,如何用模拟替换React组件

Reactjs 在使用Jest进行测试时,如何用模拟替换React组件,reactjs,mocking,jestjs,native-testing-library,Reactjs,Mocking,Jestjs,Native Testing Library,在我正在进行的项目中,我真的被困在这个问题上了,我找到的所有答案似乎都很简单,但对我来说都不管用。也许我真的不明白什么是模仿,我真的需要一些指导 我正在测试一个具有子组件的父组件,该子组件使用GraphQL从数据库中获取一些数据。在测试家长时,我不在乎孩子在做什么。我想用模拟组件(不从数据库获取数据的组件)替换子组件,这样我就可以只关注父组件 我想出了一个最简单的例子来说明我的情况。注意,我使用的是React-Native和React-Native测试库 /src/ParentComponent

在我正在进行的项目中,我真的被困在这个问题上了,我找到的所有答案似乎都很简单,但对我来说都不管用。也许我真的不明白什么是模仿,我真的需要一些指导

我正在测试一个具有子组件的父组件,该子组件使用GraphQL从数据库中获取一些数据。在测试家长时,我不在乎孩子在做什么。我想用模拟组件(不从数据库获取数据的组件)替换子组件,这样我就可以只关注父组件

我想出了一个最简单的例子来说明我的情况。注意,我使用的是React-Native和React-Native测试库

/src/ParentComponent.js

从“React”导入React;
从“react native”导入{Text,View};
从“/ChildComponent”导入ChildComponent;
常量ParentComponent=()=>(
你好,世界
);
导出默认父组件;
/src/ChildComponent.js

从“React”导入React;
从'react apollo'导入{useQuery};
从“react native”导入{View,Text};
从“graphql标签”导入gql;
const CURRENT_USER_QUERY=gql`
质疑{
当前用户{
用户名
}
}
`;
常量ChildComponent=()=>{
const{data}=useQuery(当前用户查询);
const{username}=data.currentUser;
返回(
欢迎,{username}
);
};
导出默认子组件;
/src/\uuuuu mocks\uuuuu/ChildComponent.js

从“React”导入React;
从“react native”导入{Text};
const ChildComponent=()=>欢迎您。;
导出默认子组件;
/src/ParentComponent.test.js

从“React”导入React;
从“@apollo/react testing”导入{MockedProvider};
从'@testing library/react native'导入{render};
从“../ParentComponent”导入ParentComponent;
它(`应该呈现父组件。`,()=>{
jest.mock('../ChildComponent');
常量{getByText}=render(
);
expect(getByText('Hello World')).toBeTruthy();
});
当我运行测试时,我得到以下错误

● 应该呈现父组件。
TypeError:无法读取未定义的属性“currentUser”
14 | const ChildComponent=()=>{
15 | const{data}=useQuery(当前用户查询);
>16 | const{username}=data.currentUser;
|                             ^
17 |
18 |返回(
19 |     
在ChildComponent(src/ChildComponent.js:16:29)

它仍然在使用真正的
。为什么不在
\uuuuumocks\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu在
it
声明内部调用mock时。当我将行
jest.mock('../ChildComponent');
移到顶部时,一切都正常了。因此,测试文件应该如下所示

从“React”导入React;
从“@apollo/react testing”导入{MockedProvider};
从'@testing library/react native'导入{render};
从“../ParentComponent”导入ParentComponent;
jest.mock('../ChildComponent');
它(`应该呈现父组件。`,()=>{
常量{getByText}=render(
);
expect(getByText('Hello World')).toBeTruthy();
});

您在模拟错误的文件:它应该是jest.mock(“mock/\uuumock\uuuuu/ChildComponent.js的路径”)谢谢你的回复。我试过了。这也不起作用,根据jest文档,如果文件在该目录中,应该会自动选择文件…我只是想说,祝贺你解决了你的问题。作为参考,jest文档:“注意:为了正确地模拟,jest需要jest.mock('moduleName'))与require/import语句处于同一范围。“谢谢你,Eric。有时候只需要在这里写一个问题,问题就会暴露出来。我现在在文档中看到了。谢谢。