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

8

以下是我的组件和测试代码,为什么我运行测试时confirmClickHandler方法仍然被调用?

注意:我发现当我将该方法从箭头函数更改为普通函数时,它可以被正确模拟。我错过了什么吗?

class CalendarConfirmation extends React.Component {
  ...

  confirmClickHandler = (e) =>  {
  ...
  }
}

并且是我的测试:
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();
  ...
}

嗨,如果您已经解决了这个问题,我想知道您是如何解决的。 - Neovea
2个回答

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()
})

请注意,当使用shallow而不是mount时,这种方法会失败。

3
这对我没有用,我正在使用create-react-app和enzyme-adapter-react-16。 - manas
3
测试失败,错误信息为“期望模拟函数被调用,但实际上没有被调用”。 - manas

1

你没有错过任何东西。

Jest只能模拟在require时存在的对象结构。它通过反射(而不是分析)来实现这一点,这意味着构造函数添加的属性无法被模拟。但重要的是要理解,在JS类中的fat-arrow赋值不是类方法;它是一个持有对函数引用的类属性。

https://github.com/facebook/jest/issues/6065


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接