DEV Community


Posted on

How to use jest-emotion and Enzyme to test Emotion Component Styling

Emotion is a powerful CSS-in-JS library. In this article, we will see how to start testing components' style when using emotion with React.

Using Emotion 10, React > 16.3., Enzyme v3.x

Adding Enzyme to Project

yarn add enzyme enzyme-adapter-react-16

Alternatively, you may use npm:

npm install enzyme enzyme-adapter-react-16

As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React we are using. (Here we use the adapter for React 16)

The adapter will also need to be configured before testing case.


import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

Adding jest-emotion

Jest-emotion is a Jest testing utilities for emotion. It allows us to add specific matchers to our test case.

yarn add install jest-emotion

Testing Functional Component


import React from 'react'
import {css} from 'emotion'

function Example(props){
    const {type} = props
    let color;
     switch (type) {
        case 'csv':
            color = '#ffc307';
        case 'json':
            color = '#00adef';

    return <div style={{backgroundColor:`${color}`}}>{type}</div> 

export default Example

In this case, we want to check the background-color style based on props.

Writing test cases

Here we need toHaveStyleRule matcher from jest-emotion to find the style rule of components.


import React from 'react'
import { configure, shallow } from 'enzyme'
import { matchers } from 'jest-emotion'
import Adapter from 'enzyme-adapter-react-16'
import Example from './Example'

configure({adapter: new Adapter()})

describe('test Example component',()=>{
    it('background color is #ffc307 and text is csv when props type is csv',()=>{
        const formatType = 'csv'
        const wrapper = shallow(<Example type={formatType}/>)

     it('background color is #00adef and text is json when format type is json',()=>{
        const formatType = 'json'
        const wrapper = shallow(<Example type={formatType}/>)

Top comments (0)