reactjs - 如何在开玩笑的单元测试中设置道具
问题描述
运行我的笑话单元测试时出现以下错误
警告:失败的道具类型:道具
action
在 中标记为必填Button
,但其值为undefined
。在 Button console.error node_modules/prop-types/checkPropTypes.js:20 警告:失败的道具类型:道具path
在 中标记为必需Button
,但其值为undefined
。在按钮
我尝试创建一个 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
};
我的测试“通过”。不确定这是否是误报,但我只需要错误消失。另外,如何通过单击按钮验证我传递的道具是否存在?
解决方案
这是一个工作示例:
index.tsx
:
import React from 'react';
import PropTypes from 'prop-types';
const Button = props => {
return <div className="container"></div>;
};
Button.propTypes = {
action: PropTypes.string.isRequired,
path: PropTypes.string.isRequired
};
export default Button;
index.spec.tsx
:
import React from 'react';
import Button from '.';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer';
describe('Button', () => {
it('should render without throwing an error ', () => {
const component = renderer.create(<Button action={''} path={'Cancel'} />);
expect(
shallow(<Button action={''} path={'Cancel'} />)
.find('div.container')
.exists()
).toBe(true);
});
});
单元测试结果:
PASS src/stackoverflow/55766433/index.spec.tsx (10.749s)
Button
✓ should render without throwing an error (29ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.895s
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55766433
推荐阅读
- java - 如何使用 mockito 抛出 HttpClientErrorException.Unauthorized 错误
- swift - (Swift) 如何找到调试控制台上显示的特定实例?
- excel - 使 VBA udf 与数组公式兼容
- kubernetes - 什么防火墙规则组合适用于 kubernetes 和法兰绒作为 CNI
- php - PHP 表单不插入 SQL 数据库
- git - 'git config' 命令中未显示用户详细信息
- python - 使用维基百科API
- flutter - PageView 内的 ListView - 限制水平滚动区域
- python - 日期比较有不同的数字
- swift - 继承类中类 func() 的奇怪歧义 [Swift]