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.
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.
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.
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).
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`);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With