【问题标题】:Finding class name in Jest test in styled-component在样式化组件的 Jest 测试中查找类名
【发布时间】:2020-02-29 21:27:21
【问题描述】:

我写了以下测试:

  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"的代码是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, 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}
    />
  );
}

【问题讨论】:

  • 还添加一些代码,您的组件如何使用此valid/invalid

标签: javascript jestjs enzyme styled-components


【解决方案1】:

所以你不需要(也不能)自己测试类名,因为 :valid:invalid 是状态/伪选择器。

对于来自jest-styled-componentstoHaveStyleRule,有第三个参数options,我们可以在其中提供所需的状态,例如:hover:valid

试试这个:

expect(wrapper
  .find('textarea')
  .toHaveStyleRule(
    'border-color', 
    'border-bottom: 2px solid red',
    {modifier: ':invalid'}
  )
).toBeTruthy();

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2019-05-13
    • 2019-05-30
    • 2020-03-07
    • 2021-11-25
    • 2020-04-17
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    相关资源
    最近更新 更多