Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在jest单元测试中设置道具_Reactjs_Jestjs_Enzyme - Fatal编程技术网

Reactjs 如何在jest单元测试中设置道具

Reactjs 如何在jest单元测试中设置道具,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,当我运行jest单元测试时,出现以下错误 警告:失败的道具类型:道具操作在按钮中标记为所需,但其值为未定义。 在按钮 console.error节点_模块/prop类型/checkPropTypes.js:20 警告:失败的道具类型:道具路径在按钮中标记为所需,但其值为未定义。 在按钮 我尝试创建一个const组件,该组件使用我为道具设置的值创建组件,但它仍然没有删除警告 UNIT TEST // describe what we are testing describe('Button Com

当我运行jest单元测试时,出现以下错误

警告:失败的道具类型:道具
操作
按钮
中标记为所需,但其值为
未定义
。 在按钮 console.error节点_模块/prop类型/checkPropTypes.js:20 警告:失败的道具类型:道具
路径
按钮
中标记为所需,但其值为
未定义
。 在按钮

我尝试创建一个const组件,该组件使用我为道具设置的值创建组件,但它仍然没有删除警告

UNIT TEST
// describe what we are testing
describe('Button Component', () => {

// make our assertion and what we expect to happen 
 it('should render without throwing an error', () => {
    const component = renderer.create(
        <Button action={''}
        path={'Cancel'} />)
   expect(shallow(<Button />).find('div.container').exists()).toBe(true)
 })
})

BUTTON JSX
function Button(props) {
const { action, path } = props;
  return (
     ......

  );
}

Button.propTypes = {
  action: string.isRequired,
  path: string.isRequired
};
单元测试
//描述我们正在测试的内容
描述('按钮组件',()=>{
//提出我们的主张和我们期望发生的事情
它('应该在不引发错误的情况下进行渲染',()=>{
const component=renderer.create(
)
expect(shallow().find('div.container').exists()).toBe(true)
})
})
按钮JSX
功能按钮(道具){
常量{action,path}=props;
返回(
......
);
}
Button.propTypes={
操作:string.isRequired,
路径:string.isRequired
};

我的考试“通过”。不确定这是否是假阳性,但我只需要消除错误。此外,如何通过单击按钮来验证我传递的道具是否存在?

以下是一个工作示例:

index.tsx

从“React”导入React;
从“道具类型”导入道具类型;
常量按钮=道具=>{
返回;
};
Button.propTypes={
操作:需要PropTypes.string.isRequired,
路径:PropTypes.string.isRequired
};
导出默认按钮;
index.spec.tsx

从“React”导入React;
从“”导入按钮;
从“酶”导入{shall};
从“反应测试渲染器”导入渲染器;
描述('按钮',()=>{
它('应该在不引发错误的情况下进行渲染',()=>{
const component=renderer.create();
期待(
浅()
.find('div.container')
.exists()
).托比(对);
});
});
单元测试结果:

PASS src/stackoverflow/55766433/index.spec.tsx(10.749s)
按钮
✓ 应在不引发错误的情况下进行渲染(29毫秒)
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:12.895s

源代码:

您没有在
shallow()内提供道具
action
谢谢。关于我帖子中的最后一个问题有什么建议吗?你想验证按钮组件中是否实际使用了动作和路径吗?是的,只要验证我单击按钮后,它是否具有我设置的正确动作和路径
渲染器。创建
浅层
是渲染组件的两种不同方法(一个是
react test renderer
,另一个是
enzyme
),当您使用
shallow
进行渲染时,您没有通过
操作
。如果您正在寻找有关测试
按钮
组件的反馈,请分享更多您正在测试的代码,谢谢。