How to test style for a React component attribute with Enzyme

前端 未结 10 977
刺人心
刺人心 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 08:02

    You can use this method. It returns ReactElement.

    let containerStyle = container.get(0).style;
    expect(containerStyle).to.have.property('opacity', '1');
    
    0 讨论(0)
  • 2020-12-09 08:08

    This works for me also.

    expect(containerStyle.getDOMNode()).toHaveStyle('opacity : 0');

    I had to do this to replace

    expect(getComputedStyle(checkbox.getDOMNode()).getPropertyValue('opacity')).toBe('0');

    which worked when I ran the test locally in my Intellij IDE. However when I ran it using npm t it failed. Must be something to do with how getComputedStyle was being computed in the different scenarios.

    toHaveStyle worked in both

    0 讨论(0)
  • 2020-12-09 08:09

    For me, it was a mash-up for a few answers. For those also using Jest / Enzyme:

    let containerStyle = wrapper.find('#item-id').get(0).props.style;
    
    expect(containerStyle).toHaveProperty('opacity', '1'); // ('propert', 'value')
    

    Note:

    • find returns a ShallowWrapper so we need to .get(0) the first matching element
    • .props is an attribute not a function in this instance
    • jest uses toHaveProperty not to.have.property
    0 讨论(0)
  • 2020-12-09 08:10

    I don't know if Enzyme has changed with recent versions but I needed parentheses after props in order to get the top answer to work.

    containerStyle = container.get(0).props().style;

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