Reactjs 无法在模拟子组件的jest测试中读取null属性
我有3个组成部分,结构如下:Reactjs 无法在模拟子组件的jest测试中读取null属性,reactjs,jestjs,Reactjs,Jestjs,我有3个组成部分,结构如下: const Parent = () => { // this component uses hooks return ( <div> Test <Child /> </div> ) } const Child = () => { // this component uses hooks return
const Parent = () => {
// this component uses hooks
return (
<div>
Test
<Child />
</div>
)
}
const Child = () => {
// this component uses hooks
return (
<>
Other content
<Child2>
{stuff}
</Child2>
</>
)
}
const Child2 = () => {
return <div>{children}</div>
}
const Parent=()=>{
//这个组件使用钩子
返回(
试验
)
}
常量Child=()=>{
//这个组件使用钩子
返回(
其他内容
{stuff}
)
}
常量Child2=()=>{
返回{children}
}
在我的测试中,我在嘲笑孩子,就像:
import * as renderer from "react-test-renderer";
jest.doMock("./Child", () => () => <div>MockChild</div>);
describe("Snapshot", () => {
it('renders correctly', () => {
const tree = renderer
.create(<Parent />)
.toJSON();
expect(tree).toMatchSnapshot();
});
})
import*作为“反应测试渲染器”中的渲染器;
开玩笑的多莫克(“./Child”,()=>()=>MockChild);
描述(“快照”,()=>{
它('正确渲染',()=>{
常量树=渲染器
.create()
.toJSON();
expect(tree.toMatchSnapshot();
});
})
但是在运行测试时,我得到了以下错误:TypeError:cannotreadproperty'children'为null
在stacktrace之后,我可以看到错误来自Child2中的子项。我的问题是,当我在考试中嘲笑孩子时,为什么取笑孩子2?难道它不应该被忽视吗?我如何解决这个问题?
这就是为什么您必须先doMock,然后分别导入下面的组件
import * as renderer from "react-test-renderer";
jest.doMock("./Child", () => () => <div>MockChild</div>);
// here is where you should import Parent
import Parent from './Parent';
describe("Snapshot", () => {
it('renders correctly', () => {
const tree = renderer
.create(<Parent />)
.toJSON();
expect(tree).toMatchSnapshot();
});
})
import*作为“反应测试渲染器”中的渲染器;
开玩笑的多莫克(“./Child”,()=>()=>MockChild);
//这里是您应该导入父对象的位置
从“./Parent”导入父项;
描述(“快照”,()=>{
它('正确渲染',()=>{
常量树=渲染器
.create()
.toJSON();
expect(tree.toMatchSnapshot();
});
})
顺便说一下,我建议您使用著名的而不是react测试渲染器
。它具有浅层渲染功能,完全可以实现您想要的开箱即用(模拟每个子组件)。它还提供完整渲染和静态渲染。我在导入父级之前移动了模型,但现在出现以下错误:不变冲突:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记了从中定义的文件中导出组件,或者您可能混淆了默认导入和命名导入。
您是否在Child.js
文件中导出了Child
组件?是的,我已经导出了它