【发布时间】:2018-03-28 20:56:00
【问题描述】:
我目前正在使用 Jest an Enzyme 为 React 组件编写测试。当我必须模拟一个用箭头语法编写的类属性函数时,我被卡住了:未应用模拟。
这里是测试组件的摘录:
class MaClass extends React.Component {
...
componentWillMount () {
this.getNotifications()
}
getNotifications = () => {
axios.get(window.Routing.generate(
'api_notifications_get_collection'
), {
headers: {
'Accept': 'application/json'
}
}).then(response => {
this.setState({
notifications: response.data
})
}).catch(error => {
console.log('Error : ', error)
})
}
...
}
这是测试:
import React from 'react'
import { configure, shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-15'
import NotificationsComponent from './NotificationsComponent'
configure({adapter: new Adapter()})
describe('Testing NotificationsComponent', () => {
/**
* This should call getNotifications
*/
test('getNotifications should be called', () => {
let wrapper = shallow(<NotificationsComponent />)
const getMock = jest.fn()
wrapper.instance().getNotifications = getMock
wrapper.update()
expect(getMock).toHaveBeenCalled()
})
})
就阅读而言,这是常规方法的正确方法。但是用箭头语法写的类属性函数好像不能这样mock。
我的终端抛出一个关于被测组件方法内部的错误:
TypeError: Cannot read property 'generate' of undefined
这意味着mock没有通过。
谁能指出我的错误在哪里?谢谢。
【问题讨论】: