我想测试当 prop 具有特定值 true
或 false
时是否正在渲染正确的组件。
这是代码:
/* eslint-disable react/default-props-match-prop-types */
import React, { Fragment } from 'react';
import moment from 'moment';
import ILicense from 'dto/ILicense';
import Icon from 'components/Icon';
export interface Props {
license?: ILicense;
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const LicenseInfo = <T extends object>({ license }: Props & T) => (
<Fragment>
{license ? (
<Fragment>
<div className="py-5 mx-3">
{license.isValid? (
<div>
<Icon icon="check" className="fa-lg text-success mr-2" />
License is Valid
</div>
) : (
<div>
<Icon icon="exclamation-circle" className="fa-lg text-danger mr-2" />
License has expired
</div>
)}
</Fragment>
) : null}
</Fragment>
);
LicenseInfo.defaultProps = {
clientId: '',
expiry: null,
isValid: true,
};
export default LicenseInfo;
这是我的测试用例:如果 prop isValid 为 true
,则使用 icon 属性 check
渲染 Icon 组件,否则使用另一个。
这是我的测试:
it('expect to show check Icon when license.isValid prop is true', () => {
const wrapper = mount<LicenseInfo>(<LicenseInfo isValid="true">Test</LicenseInfo>);
const check = wrapper.find(<Icon icon="check" />).props;
console.log(check);
expect(check).toBeTruthy();
});
我认为问题出在检查
上。 I console.log
它并获取此 ReactWrapper {}
..
关于如何正确执行此操作的任何想法...?谢谢!!
最佳答案
来自 Enzyme'e 文档 find()
期待EnzymeSelector
待通过。这应该是
- 类似 CSS 的选择器(在您的情况下为
Icon[icon=check]
) - 构造函数名称(
图标
) - 显示名称(
'图标'
) - 具有属性的对象
您正在向那里传递 JSX 元素,因此什么也找不到。
所以我相信
it('expect to show check Icon when license.isValid prop is true', () => {
const wrapper = mount<LicenseInfo>(<LicenseInfo isValid="true">Test</LicenseInfo>);
const iconType = wrapper.find(Icon).prop('icon');
expect(iconType).toEqual('check');
});
应该适合你
关于javascript - enzyme |有条件地检查 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54785523/