Rohith Nair
Rohith Nair

Reputation: 1070

Jest mocking with react calling actual event handler after calling mock function

I have this component test

    const component = mount(<MemoryRouter><Login/></MemoryRouter>);
    const emailField = component.find('input[type="email"]');
    const passwordField = component.find('input[type="password"]');
    const mockedSubmitFunction=jest.fn();
    component.find(Login).instance().onSubmit=mockedSubmitFunction;
    emailField.simulate('change', { target: { value: testEmail } });
    passwordField.simulate('change', { target: { value: testPassword } });
    component.find('form').simulate('submit');
    expect(mockedSubmitFunction).toBeCalled();

and in the component i have

in constructor :-

this.onSubmit = this.onSubmit.bind(this);

and the eventhandler

   onSubmit(event) {
   event.preventDefault(); 

when i put a breakpoint in onSubmit it is coming to the component function after executing the mocked onSubmit, why is this happening.

I assumed it will only call the mocked onSubmit.

What am I doing differently?

CodeSandbox :https://codesandbox.io/s/q95lv7vlrw

But the sandbox is showing Could not find module in path: 'object-inspect/util.inspect' relative to '/node_modules/object-inspect/index.js' for some reason, which is unrelated i guess

Upvotes: 1

Views: 7521

Answers (1)

Andy Theos
Andy Theos

Reputation: 3346

So you got function mocked, but actual onSubmit is called. Instead if you want to call only mocked fn you have to provide it (as a prop in your test spec for example).

const mockedSubmitFunction = jest.fn(event => {
  console.log("Mocked function");
});
const component = mount(
  <MemoryRouter>
    <Login login={mockedSubmitFunction} />
  </MemoryRouter>
);

I updated sandbox for you.

You can additionally check this explained example on form testing.

Update: i suppose that the actual problem OP has was that mock function was firing, but it was copied to instance, thus expect...toBeCalled() fails (actual mockedFn was not called). You can avoid these problems by passing mocked function as a prop, spying on a function, etc.

Upvotes: 1

Related Questions