Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

jestjs

I'm building unit tests with JestJS (npm jest-cli) and need to validate that a 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(''); 
});

That results in iconHeight === '' instead of a value of pixels.

I wonder if window is being mocked by Jest. Or if window isn't supported.

like image 537
cuadraman Avatar asked Feb 01 '15 20:02

cuadraman


People also ask

How would you test a function inside a React component using Jest?

import Todo from '../app/todo'; import React from 'react'; import { mount } from 'enzyme'; test('Todo component renders the text of the todo', () => { }); I also import mount from Enzyme. The mount function is used to render our component and then allow us to inspect the output and make assertions on it.

How would you test the React components using Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

What is the best way to test React components?

There are a few ways to test React components. Broadly, they divide into two categories: Rendering component trees in a simplified test environment and asserting on their output. Running a complete app in a realistic browser environment (also known as “end-to-end” tests).


1 Answers

This is fairly easy using jest-dom and react-testing-library.

Tiny example:

component.js

const Component = () => <div style={{left: '4rem'}}>Left component</div>;

component.test.js

test("left shoud be 4rem", () => {
    const { getByText } = render(<Component />);
    expect(getByText(/left component/i).parentElement).toHaveStyle(`left: 4rem`);
})
like image 185
creimers Avatar answered Oct 27 '22 00:10

creimers