当我运行我的 jest 单元测试时出现以下错误
Warning: Failed prop type: The prop
action
is marked as required inButton
, but its value isundefined
. in Button console.error node_modules/prop-types/checkPropTypes.js:20 Warning: Failed prop type: The proppath
is marked as required inButton
, but its value isundefined
. in Button
我尝试创建一个 const 组件,该组件使用我为 props 设置的值创建组件,但它仍然没有删除警告。
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
};
我的测试“通过”。不确定这是否是误报,但我只需要错误消失。另外,我如何根据点击按钮来验证我传递的 Prop 是否存在?
最佳答案
这是一个工作示例:
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
关于reactjs - 如何在 Jest 单元测试中设置 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55766433/