React + Jest + Enzyme

遇到的小坑

1.在引入测试的组件时,有时候我们的组件是以一个高阶的组件的形式导出的,而在我们测试的时候,我们只需要测试这个组件本身,不需要引入这个组件的封装体进行测试。
比如我们的组件A.js如下

	class  A  extends Component{
		//....
	}
	export default HOC(A);

此时我们需要在对A.js进行如下更改

	export class A extends Component{
		//...
	}
	export default HOC(A)

也就是加了一个export, 将A单独导出
同时在测试文件A.test.js中, 导入A

	import { A } from 'A.js';

如此我们在A.test.js中拿到的就是一个完整的A组件而不是HOC封装的一个高阶A组件

2.component中引入了echart, 在进行测试时会提示报错
在引入echart时,需要对echart的getInstanceByDom方法进行模拟

	beforeAll(()=>{
		spy = jest.spyOn(echarts, 'getInstanceByDom').mockImplementation(() => {
	        return {
	            hideLoading: jest.fn(),
	            setOption: jest.fn(),
	            showLoading: jest.fn(),
	            clear: jest.fn(),
	            resize: jest.fn(),
	            on: jest.fn(),
	        }
	    })
	})	
    afterAll(() => {
	    spy.mockRestore()
	})

3.在component中使用了ref, 导致测试函数中引用ref的地方报错
目前查阅的是,在enzyme中不支持ref功能,我自己尝试的一种替代解决方案是,手动进行ref的赋值
这里以echartRef为列

Component

	constructor(){
		super(props);
    	this.EChart = React.createRef();
    	...
	}

	render(){
		...
		<ReactEcharts ref={this.EChart} option={this.state.option} />
		...
	}

Test

	beforeAll(()=>{
		spy = jest.spyOn(echarts, 'getInstanceByDom').mockImplementation(() => {
	        return {
	            hideLoading: jest.fn(),
	            setOption: jest.fn(),
	            showLoading: jest.fn(),
	            clear: jest.fn(),
	            resize: jest.fn(),
	            on: jest.fn(),
	        }
	    })
	    com = shallow(<DashboardChart  defaultChooseChart="runtime" />, {disableLifecycleMethods: true})
    	com.instance().EChart.current = {
        	getEchartsInstance: ()=>echarts.getInstanceByDom()
    	}
	})

如此,在测试函数中使用this.EChart.current的方法时,就不会报错.

参考链接:
1.https://stackoverflow.com/questions/54570400/testing-the-react-createref-api-with-enzyme
2.https://stackoverflow.com/questions/52440180/react-enzyme-how-to-test-reference-function

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章