Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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();
  ...
}
like image 283
JoshieWashie Avatar asked Aug 04 '17 16:08

JoshieWashie


2 Answers

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.

like image 188
jorrebor Avatar answered Oct 16 '22 23:10

jorrebor


You are not missing anything.

Jest can only mock the structure of objects that are present at require time. 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; it's a class property holding a reference to a function.

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

like image 21
Leftwing Avatar answered Oct 16 '22 23:10

Leftwing