How to test style for a React component attribute with Enzyme

前端 未结 10 976
刺人心
刺人心 2020-12-09 07:21

I am trying to test a style attribute for a React component. What is the best way to get style params in the test?

At this moment, my best option is to test if the H

相关标签:
10条回答
  • 2020-12-09 07:45
    const elem = wrapper.find(Element);
    expect(getComputedStyle(elem.getDOMNode()).getPropertyValue('opacity')).toBe('0.4');
    
    0 讨论(0)
  • 2020-12-09 07:52

    If you use jest-styled-components then you can use toHaveStyleRule as follows:

    expect(component.find('#item-id')).toHaveStyleRule('opacity', 'red');

    0 讨论(0)
  • 2020-12-09 07:52

    I would like to add that the following props() method can also be used. https://airbnb.io/enzyme/docs/api/ShallowWrapper/props.html

    let containerStyleOpacity = container.get(0).props().style.opacity; expect(containerStyleOpacity).to.be.equal('1');

    0 讨论(0)
  • 2020-12-09 07:55

    Slightly elaborating on others' answers:

    expect(component.find('#item-id').prop('style')).toHaveProperty('backgroundSize', '100%');
    

    This will check the style prop of #item-id. This prop is an object and here toHaveProperty matcher checks if this object contains backgroundSize property and if its value is 100%.

    This way other style properties are ignored.

    0 讨论(0)
  • 2020-12-09 07:56

    Have a look at chaiEnzyme, which provides a handy little assertion you can use with chai to check whether a wrapper has a particular style (https://github.com/producthunt/chai-enzyme#stylekey-val), should help make your tests look a little cleaner.

    0 讨论(0)
  • 2020-12-09 07:57

    expect(component.find('#item-id').prop('style')).to.deep.equal({display: 'none'})

    0 讨论(0)
提交回复
热议问题