简体   繁体   English

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

[英]Jest - mock fat arrow function within React component

Given my component and test below, why does my confirmClickHandler method still get called when I run my test? 鉴于我的组件和测试如下,为什么我运行测试时仍会调用confirmClickHandler方法?

Note: I noticed that when I change the method from a fat arrow function to just a regular function, it gets mocked out correctly. 注意:我注意到当我将方法从胖箭头函数更改为常规函数时,它会被正确地模拟出来。 What am I missing here? 我在这里错过了什么?

class CalendarConfirmation extends React.Component {
  ...

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

and my test: 和我的测试:

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

This works for me: 这对我有用:

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

Note however, that this fails when using shallow instead of mount. 但请注意,使用shallow而不是mount时会失败。

You are not missing anything. 你没有遗漏任何东西。

Jest can only mock the structure of objects that are present at require time. Jest只能模拟在需要时出现的对象的结构。 It does it by reflection (not by analysis), which means that properties that get added by the constructor cannot be mocked. 它通过反射(而不是通过分析)来实现,这意味着不能模拟由构造函数添加的属性。 It's important to understand though that a fat-arrow assignment in a class in JS is not a class method; 重要的是要理解JS中的类中的胖箭分配不是类方法; it's a class property holding a reference to a function. 它是一个包含对函数的引用的类属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM