How to unit test the style of a React component using Jest.js?

I am building unit tests with JestJS (npm jest-cli) and I need to verify that the ReactJS element contains the CSS styles that I'm looking for.

I tried to check

it('should highlight the selected option in the drop-down list', function() { var iconTriangleDown = TestUtils.findRenderedDOMComponentWithClass(dropList, 'icon-triangle-down'); var iconHeight = window.getComputedStyle(iconTriangleDown.getDOMNode(), null).height; expect(iconHeight).notToEqual(''); }); 

This results in iconHeight === '' instead of the pixel value.

I wonder if the window from Jest is taunting. Or if the window is not supported.

+6
source share
3 answers

You can test styles, although snapshot tests, but Jest does not support evaluating component styles through statements, that is, through expect .

To do this, you need to combine Jest with the enzyme , chai and chai-farme .

This combination will allow you to write tests, like this simple example:

 it('should render style', () => { chai.expect(shallow( <div style={{ left: '4rem' }} /> )).to.have.style('left', '4rem'); }); 

First create the installation file and add it to the jest.setupFiles array in package.json. For an overview of this option, see the Jest documentation .

This is my settings file:

 // test/setup.js import React from 'react'; import chai from 'chai'; import chaiEnzyme from 'chai-enzyme'; import { shallow, render, mount } from 'enzyme'; // Add commonly used methods and objects as globals global.chai = chai; global.mount = mount; global.React = React; global.render = render; global.shallow = shallow; chai.use(chaiEnzyme()); 

This is my .json package:

 { "jest": { "setupFiles": [ "./test/setup.js" ] } } 

Now that you need it, you can access the Chai chai.expect API through chai.expect and the Jest chai.expect API through expect .

+3
source

Someone who finds this topic, Jest Enzyme now has a statement for testing styles: toHaveStyle: https://github.com/blainekasten/enzyme-matchers/blob/master/README.md#tohavestylestylekeystring-stylevalueany

The problem for me was that, seeing the code, I only test objects, and I have many styles that are arrays (I use React Native BTW), so it did not work for me.

I am doing this method to test for a specific style:

 const render = wrapper.dive(); expect(render.find("[testID='bannerStamp']").get(0).props.style[0].right).toBe(7); 
+2
source

Test Styles? I think this may be the best approach for testing styles https://github.com/Huddle/PhantomCSS , I use only Jest to test the element and element behavior, not visual.

If you really want to do what you are doing, why don't you just use jQuery for devDependency to help you get the dom node attributes, and if the drop-down list of your element is opened with just a click, you probably want to set a timeout and some behavior dom before executing the expect () function.

-1
source

Source: https://habr.com/ru/post/981844/


All Articles