我写了以下测试:
it('componentDidUpdate should mount and change props', () => {
const onChange = jest.fn();
const wrapper = enzyme
.mount(
<JsonInput
onChange={onChange}
onValueChange={mockOnValueChange}
value={exampleJsonStringValidated}
/>,
{ wrappingComponent: withTestThemeWrapper },
);
console.log(wrapper.debug());
expect(wrapper.find(JsonInput).hasClass('valid')).toEqual(true);
wrapper.setProps({ value: exampleJsonStringNotValidated });
expect(wrapper.find(JsonInput).hasClass('invalid')).toBe(true);
});
和console.log
显示:
<JsonInput onChange={[Function: mockConstructor]} onValueChange={[Function: mockConstructor]} value="{"firstName":"John","lastName":"Doe","age":210}">
<styled.textarea onChange={[Function]} value="{"firstName":"John","lastName":"Doe","age":210}" height="">
<StyledComponent onChange={[Function]} value="{"firstName":"John","lastName":"Doe","age":210}" height="" forwardedComponent={{...}} forwardedRef={{...}}>
<textarea onChange={[Function]} value="{"firstName":"John","lastName":"Doe","age":210}" height="" className="sc-bdVaJa lavZWj" />
</StyledComponent>
</styled.textarea>
</JsonInput>
在组件中,代码className="sc-bdVaJa lavZWj"
是valid
和invalid
,但现在我看到没有可读的类名,如何对其进行测试?
组件(样式部分)
export const StyledTextArea = styled.textarea<{ height: string }>`
margin: 0;
box-sizing: border-box;
width: 350px;
outline: none;
border: none;
height: ${props => props.height};
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.23);
background-color: ${props => props.theme.palette.foreground};
color: ${props => props.theme.palette.text};
cursor: text;
&:focus{
border-bottom: 2px solid ${props => props.theme.palette.active};
}
&:valid{
border-bottom: 2px solid ${props => props.theme.palette.positive};
}
&:invalid{
border-bottom: 2px solid ${props => props.theme.palette.negative};
}
`;
并渲染:
render() {
// to exclude unknown property 'onValueChange' for JsonInput for DevTools
const { height = '', onValueChange, ...restProps } = this.props;
return (
<StyledTextArea
ref={this.JsonInputRef}
{...restProps}
onChange={this.handleValueChange}
height={height}
/>
);
}
答案 0 :(得分:0)
因为:valid
和:invalid
是状态/伪选择器,所以您不需要(也不能)自己测试类名。
对于jest-styled-components
中的Lightbend forum,有第三个参数options
,我们可以在其中提供所需的状态,例如:hover
或:valid
。
尝试一下:
expect(wrapper
.find('textarea')
.toHaveStyleRule(
'border-color',
'border-bottom: 2px solid red',
{modifier: ':invalid'}
)
).toBeTruthy();