Jest - React组件中的模拟胖箭头函数

Jos*_*hie 6 javascript reactjs jestjs babel-jest

鉴于我的组件和测试如下,为什么我的confirmClickHandler方法在我运行测试时仍然被调用?

注意:我注意到当我将方法从胖箭头函数更改为常规函数时,它会被正确地模拟出来.我在这里错过了什么?

class CalendarConfirmation extends React.Component {
  ...

  confirmClickHandler = (e) =>  {
  ...
  }
}
Run Code Online (Sandbox Code Playgroud)

和我的测试:

import React from 'react';
import {mount} from 'enzyme';
import CalendarConfirmation from '../components/CalendarConfirmation';

describe('Test CalendarConfirmation', () => {
  let calendarConfirmation;
  calendarConfirmation = mount (<CalendarConfirmation />);
  calendarConfirmation.instance().confirmClickHandler = jest.fn();
  ...
}
Run Code Online (Sandbox Code Playgroud)

jor*_*bor 2

这对我有用:

import React from 'react'
import { mount, shallow } from 'enzyme'

class Foo extends React.Component {
  // babel transpiles this too Foo.prototype.canMock
  protoMethod () {
    // will be mocked
  }

  // this becomes an instance property
  instanceMethod = () => {
    return 'NOT be mocked'
  }

  render () {
    return (<div>{`${this.protoMethod()} ${this.instanceMethod()}`}</div>)
  }
}

Foo.prototype.protoMethod = jest.fn().mockReturnValue('you shall')

it('should be mocked', () => {
  const mock = jest.fn().mockReturnValue('be mocked')
  const wrapper = mount(<Foo />)
  wrapper.instance().instanceMethod = mock
  wrapper.update()
  expect(mock).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)

shallow但请注意,当使用而不是安装时,这会失败。

  • 这对我不起作用我正在使用 create React 和酶-adapter-react-16 (3认同)
  • 测试失败,并显示“预期模拟函数已被调用,但并未被调用。” (3认同)