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
const elem = wrapper.find(Element);
expect(getComputedStyle(elem.getDOMNode()).getPropertyValue('opacity')).toBe('0.4');
If you use jest-styled-components then you can use toHaveStyleRule
as follows:
expect(component.find('#item-id')).toHaveStyleRule('opacity', 'red');
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');
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.
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.
expect(component.find('#item-id').prop('style')).to.deep.equal({display: 'none'})