Jest / Enzyme不能模拟类属性

时间:2017-10-17 08:14:50

标签: reactjs jestjs enzyme

我目前正在用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()
  })
})

就阅读而言,这是常规方法的正确方法。但似乎用箭头语法编写的类属性函数不能以这种方式进行嘲弄。

我的终端抛出了关于测试组件方法内部内容的错误:

TypeError: Cannot read property 'generate' of undefined

这意味着模拟不会通过。

有人会指出我的错误在哪里吗?感谢。

2 个答案:

答案 0 :(得分:0)

你正在使用错误的生命周期钩子。 componentWillMount被称为&#34;内部&#34; shallow(<NotificationsComponent />)。因此,已调用原始getNotifications

wrapper.update()强制重新渲染并且不重新安装组件,因此您对模拟的分配无法达到预期的效果。

答案 1 :(得分:0)

问题是没有好的方法可以模拟作为箭头函数的类属性。到目前为止,我发现的最佳解决方法是将class属性移至类方法并在构造函数中绑定该方法。

constructor(props) {
    super(props);
    this.getNotifications = this.getNotifications.bind(this);
}

getNotifications() {...}

然后在测试中,您将可以正确使用jest.spyOn()

const spy = jest.spyOn(MaClass.prototype, 'getNotifications');

以下是一些其他信息: https://remarkablemark.org/blog/2018/06/13/spyon-react-class-method/

希望有帮助!