【问题标题】:Jest - mock fat arrow function within React componentJest - React 组件中的模拟胖箭头函数
【发布时间】:2018-01-12 15:36:40
【问题描述】:

鉴于我的组件和下面的测试,为什么我的 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();
  ...
}

【问题讨论】:

  • 嗨,如果你这样做了,我很想知道你是怎么想出来的。

标签: javascript reactjs jestjs babel-jest


【解决方案1】:

这对我有用:

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 时,这会失败。

【讨论】:

  • 这对我不起作用,我正在使用 create react 和酶适配器反应 16
  • 测试失败,“预期的模拟函数已被调用,但未被调用。”
【解决方案2】:

你没有错过任何东西。

Jest 只能模拟存在于 需要时间。它通过反思(而不是通过分析)来实现,这意味着 构造函数添加的属性不能被模拟。 重要的是要理解,在 JS中的class不是类方法;这是一个持有 引用函数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2021-09-26
    • 2023-03-12
    • 2019-05-13
    相关资源
    最近更新 更多