Muk*_*esh 6 testing reactjs jestjs
我为下载文件创建了一个组件,它带有一些道具并在按钮点击时下载文件,它有两个函数调用showLoader和HideLoader
组件:下面是组件代码,它点了一些道具并在点击该用户下载文件时创建了一个下载按钮.
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
Run Code Online (Sandbox Code Playgroud)
测试我在测试组件,不能测试用户点击按钮下载时,它给callShowLoader不是函数错误
import React from 'react'
import { shallow, mount } from 'enzyme'
import DownloadFile from '../index.js'
import toJson from 'enzyme-to-json'
import axios from 'axios'
describe('<DownloadFile />', () => {
const props = {
callHideLoader: jest.fn(),
callShowLoader: jest.fn(),
title: 'Download Excel Report'
}
it('should render button title properly', () => {
const wrapper = shallow(<DownloadFile {...props}/>)
expect(wrapper.find('button').prop('title')).toEqual(props.title)
})
it('should call download file', () => {
const callShowLoader = jest.fn()
const wrapper = shallow(<DownloadFile {...props} callShowLoader={callShowLoader} />)
wrapper.find('button').simulate('click')
expect(callShowLoader).toHaveBeenCalled()
})
it('should match intial layout', () => {
const wrapper = shallow(<DownloadFile {...props}/>)
expect(wrapper.getElements()).toMatchSnapshot()
})
})
Run Code Online (Sandbox Code Playgroud)
小智 4
DownloadFile 上的 onClick 属性被完全忽略,因为您在 DownloadFile 组件的实现中没有使用它。
使用 jest.fn() 初始化 callShowLoader 和 callHideLoader,将它们传递给 DownloadFile 组件(初始化 mountWrapper 时),然后模拟 onClick 按钮并测试 callShowLoader 和 callHideLoader 是否都被调用。
| 归档时间: |
|
| 查看次数: |
934 次 |
| 最近记录: |