Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR: Expected mock function to have been called

I am trying to test onClick of a span tag of a react component.

<span id="A" onClick={this.changeImage}> Image A</span>

Want to test if 'onClick' the 'changeImage' function is being called or not!

// test.js

describe('Tests', () => {
const wrapper = shallow(<Image />);
it('Should render without exploading', () => {
    expect(wrapper).toHaveLength(1);
});

it('Should call changeImage() function on click', () => {
    wrapper.instance().changeImage = jest.fn();
    wrapper.update();
    wrapper.find('#A').simulate('click', { target: { id: 'A' } });
    expect(wrapper.instance().changeImage).toHaveBeenCalled();
    });
});

Also tried this -

it('Should call changeImage() function on click', () => {
    const spy = jest.spyOn(wrapper.instance(), 'changeImage');
    wrapper.find('#A').simulate('click', { target: { id: 'A' } });
    expect(spy).toHaveBeenCalled();
});

Both returning the same error. // Error

● Tests › Should call changeImage() function on click

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.

Can someone please point out what am I doing wrong? Thanks.

like image 281
remelkabir Avatar asked Oct 29 '22 22:10

remelkabir


1 Answers

// fixed mistake

describe('Tests', () => {
it('Should render without exploading', () => {
    const wrapper = shallow(<Image />);
    expect(wrapper).toHaveLength(1);
});

it('Should call changeImage() function on click', () => {
    const spy = jest.spyOn(Image.prototype, 'changeImage');
    const wrapper = shallow(<Image/>);
    wrapper.find('#A').simulate('click', { target: { id: 'A' } });
    expect(spy).toHaveBeenCalled();
    spy.mockClear();//clearing the mock functions
    });    
 });

Putting the wrapper after the jest.spyOn() mock function made the test work.

In the case of mocking function the order of declaring const matters. Spy needs to be declared first then the wrapper. Declaring wrapper before spy will cause this error:

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.
like image 51
remelkabir Avatar answered Nov 08 '22 10:11

remelkabir