遇到的小坑
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