DEV Community

Kira
Kira

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.

Note:
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.

src/example.test.js

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

src/example.js

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

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

    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.

src/example.test.js

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()})
expect.extend(matchers)

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}/>)
        expect(wrapper.text()).toEqual('csv')
        expect(wrapper).toHaveStyleRule('background-color','#ffc307')
    })

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

Top comments (0)