在样式组件中的Jest测试中查找类名

我写了以下测试:

  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","age":210}" height="">
      <StyledComponent onChange={[Function]} value="{"firstName":"John","age":210}" height="" forwardedComponent={{...}} forwardedRef={{...}}>
        <textarea onChange={[Function]} value="{"firstName":"John","age":210}" height="" classname="sc-bdVaJa lavZWj" />
      </StyledComponent>
    </styled.textarea>
  </JsonInput>

在组件中,代码classname="sc-bdVaJa lavZWj"validinvalid,但现在我看到没有可读的类名,如何对其进行测试?

组件(样式部分)

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.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}
    />
  );
}
dgdfhdshdsh 回答:在样式组件中的Jest测试中查找类名

因为: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();
本文链接:https://www.f2er.com/3165969.html

大家都在问