Wednesday, 11 July 2018

How to test below component in React using JEST

I created a component for Download File which takes some props and download the file on button click, its has two function which call showLoader and HideLoader

Component: Below is component code which takes some props and created a Download button on click that user download file.

import React from 'react'
import FileSaver from 'file-saver'
import axios from 'axios'

const DownloadFile = (props) => {

  const { url, title, callShowLoader, callHideLoader } = props

  const callDownloadFile = () => {
    callShowLoader()
    axios.get(url, { responseType: 'blob' }).then(res => {
      const fileName = res.headers['content-disposition'].match(/\"(.*?)"/)
      const fileToDownload = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=charset=utf-8'})
      FileSaver.saveAs(fileToDownload, fileName[1])
      callHideLoader()
    })
  }

  return (<button className='mck-button-primary' title={title} onClick={e => callDownloadFile()}>
            <span className={"mck-icon__download mck-icon-no-pad"} />
          </button>)
}

export default DownloadFile

Test Here i am testing the component, not able to test when user clicks on button for download, its giving callShowLoader is not function error

import React from 'react'
import { shallow, mount } from 'enzyme'
import DownloadFile from '../index.js'
import toJson from 'enzyme-to-json'

describe('<DownloadFile />', () => {
  let shallowWrapper, mountWrapper, props
  const doneDownloadFile = jest.fn()

  beforeEach(() => {
    props = { title: 'Download Excel Report'}
    shallowWrapper = shallow(<DownloadFile {...props} />)
    mountWrapper = mount(<DownloadFile {...props} onClick={doneDownloadFile} />)
  })

  it('should render button title properly', () => {
    expect(shallowWrapper.find('button').prop('title')).toEqual(props.title)
  })

  it('should call download file', () => {
    const button = mountWrapper.find('button')
    button.simulate('click')
    expect(doneDownloadFile).toHaveBeenCalled()
  })

  it('should match intial layout', () => {
    expect(shallowWrapper.getElements()).toMatchSnapshot()
  })
})



from How to test below component in React using JEST

No comments:

Post a Comment