Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy componentWillMount using jest and enzyme

I am trying to test whether componentWillMount was called and for that my test is

test('calls `componentWillMount` before rendering', () => {
  let fn = jest.fn(SomeComponent.prototype.componentWillMount)
  mount(<SomeComponent />)
  expect(fn).toHaveBeenCalled()
})

But even though the componentWillMount method is called, the test does not pass. What am I missing here?

like image 729
sidoshi Avatar asked Jan 11 '17 18:01

sidoshi


2 Answers

Try this:

test('calls `componentWillMount` before rendering', () => {
  const onWillMount = jest.fn();
  SomeComponent.prototype.componentWillMount = onWillMount;
  mount(<SomeComponent />);

  expect(onWillMount).toBeCalled();
});
like image 59
devellopah Avatar answered Sep 30 '22 11:09

devellopah


I would first spy on the component's componentWillMount method but also use .and.CallThrough() to prevent it from mocking its contents. Hope this helps:

it('should check that the componentWillMount method is getting called', () => {
    spyOn(SomeComponent.prototype, 'componentWillMount').and.callThrough();

    const wrapper = mount(<SomeComponent />);

    expect(wrapper).toBeDefined();
    expect(SomeComponent.prototype.componentWillMount).toHaveBeenCalledTimes(1);
});
like image 22
manosim Avatar answered Sep 30 '22 09:09

manosim