How to test style for a React component attribute with Enzyme

穿精又带淫゛_ 提交于 2019-11-29 05:24:55

You can use this method. It returns ReactElement.

let containerStyle = container.get(0).style;
expect(containerStyle).to.have.property('opacity', '1');

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

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.

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

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

const elem = wrapper.find(Element);
expect(getComputedStyle(elem.getDOMNode()).getPropertyValue('opacity')).toBe('0.4');

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.

You can try using a regex on .html() value:

const span = mount(<Test />).find('span');
expect(span.html().match(/style="([^"]*)"/i)[1]).toBe('color: #000;');

Or to get any other attribute:

const getAttr = ( html, name ) => html.match(new RegExp(`${name}="([^"]*)"`, 'i'))[1];
let type = getAttr('<input type="text" value=""/>', 'type');
console.log(type);  // "text"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!