desirelabs
11/17/2017 - 8:36 AM

Usefull tests for React

Tests for React using Jest, Enzyme and react-test-renderer

import React from 'react'
import { configure, shallow, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

import Component from './Component'

configure({adapter: new Adapter()})

describe('Testing Component', () => {
  /**
   * test snapshot matches
   */
  it('Should match snapshot', () => {
    expect.assertions(1)
    const wrapper = renderer.create(<Component />)
    const tree = wrapper.toJSON()
    expect(tree).toMatchSnapshot()
  })
  
  /**
   * test state to update after input changed
   */
  it('Should update state when inputs changes', () => {
    expect.assertions(1)
    const wrapper = shallow(<Component />)
    wrapper.find('input-target').simulate('change', {target: {value: 'input value', name: 'input-name'}})
    expect(wrapper.state('input-name')).toBe('input value')
  })
  
  /**
   * test callback function after input changed
   */
  it('Should call callback function when inputs changes', () => {
    expect.assertions(1)
    const wrapper = shallow(<Component />)
    const instance = wrapper.instance()
    const spy = jest.spyOn(instance, 'callback')
    wrapper.find('input-target').simulate('change', {target: {value: 'input value', name: 'input-name'}})
    expect(spy).toHaveBeenCalled()
  })
  
  /**
   * test if a not exists based on state
   */
  it('Should remove error alert if message is not set in state', () => {
    expect.assertions(1)
    const wrapper = shallow(<Component />)
    wrapper.setState({error: ''})
    expect(wrapper.find('.alert-danger').exists()).toBe(false)
  })
  
  /**
   * test html tag attributes
   */
  it('Should have attribute [attribute] to be set with [value]', () => {
      const wrapper = mount(<Component />)
      const htmlTag = wrapper.find('input[name="name"]').render()
      expect(htmlTag[0].attribs.id).toBe('name')
  })
  
  /**
   * test html tag exists
   */
  it('Should html tag exist', () => {
    const wrapper = shallow(<Component />)
    expect(wrapper.find('.my-tag-class').exists()).toBe(true)
  })
})