javascript - 如何在 Jest 和 Enzyme 中验证 React 道具?
问题描述
所以我试图学习 React 中的测试,我有这个:Button.js
和Button.test.js
该问题与以下代码一起注释:
// Button.js
import React from 'react';
import { string, bool, func } from 'prop-types';
import { StyledButton } from './styled'
const Button = ({
size,
text,
}) => (
<StyledButton
size={size}
// the test will alway fail with result:
// Expected value to be: "Join us"
// Received: undefined
// Unless I add add this line below
text={text}
>
{text} // but the text props is here. That is my current practice of passing the props to the children, am I missing anything?
</StyledButton>
);
Button.propTypes = {
size: string,
text: string,
};
Button.defaultProps = {
size: '',
text: '',
};
export default Button;
// Button.test.js
import React from 'react';
import { shallow } from 'enzyme';
import Button from '../../components/Button/Button';
describe('Component: Button', () => {
const minProps = {
text: '',
size: '',
};
it('renders a button in size of "small" with text in it', () => {
const wrapper = shallow(
<Button {...minProps} size="small" text="Join us" />
);
expect(wrapper.prop('size')).toBe('small');
expect(wrapper.prop('text')).toBe('Join us');
});
});
// StyledButton
import Button from 'antd/lib/button';
const StyledButton = styled(Button)`
&.ant-btn {
padding: 0 24px;
${({ size }) => {
if (size === 'small') {
return css`
font-size: 14px;
line-height: 32px;
`;
}
return null;
}};
`;
export { StyledButton };
有谁知道为什么测试不会通过,除非我将道具传递给StyledButton
?
解决方案
在断言props之前,您需要StyledButton
在组件中找到Button
// Button.test.js
import React from 'react';
import { shallow } from 'enzyme';
import Button from '../../components/Button/Button';
import { StyledButton } from './styled'
describe('Component: Button', () => {
const minProps = {
text: '',
size: '',
};
it('renders a button in size of "small" with text in it', () => {
const wrapper = shallow(
<Button {...minProps} size="small" text="Join us" />
);
expect(wrapper.find(StyledButton).prop('size')).toBe('small');
expect(wrapper.find(StyledButton).prop('text')).toBe('Join us');
});
});
推荐阅读
- mysql - SQL 按功能分组以仅对最新数据进行分类
- java - 如何从另一个 Fragment 调用一个 Fragment 的方法?
- doxygen - doxygen 可以在围栏代码块中突出显示哪些语言
- javascript - Algolia vue Instantsearch 动态设置搜索查询
- java - 如何正确配置Spring应该选择哪个实现?
- text-mining - Quanteda 合并一元和二元
- python - 如果多个测试有特定异常,则停止 pytest 测试
- angular - 需要定期暂停 Carousel 动画并调用一个函数
- django - 返回与 ManyToManyField 相关的对象的 JSON
- java - HttpClient sendAsync 丢失 MDC 日志信息