0

following that answer: Jest -- Mock a function called inside a React Component

I have this test (trying to mock fireAnalytics imported function, like so:

mytest.test.js


`.import { fireAnalytics } from "@module/js-utils/lib";
jest.mock('@module/js-utils/lib', () => ({ fireAnalytics: jest.fn(() => 'hello!') }))`

`

  it('renders component', () => {
        const WrappedMyComponent = hoc(Foo);   
         const props = {};


      const wrapper = mount(
        <WrappedMyComponent {...props} />
      );
    const event = {
       // target: {
       //    id: 'test'
        // }
     };
     // simulate click should call `handleInputClick`
     wrapper.find('input').props().onClick(event);`

component

import { fireAnalytics } from "@module/js-utils/lib";

handleInputClick(e) {
        // I need to mock this function. But currently the test
goes here and asks for the e.target.id
        fireAnalytics({
            event: "",
            category: "",
            action: `Clicked on the ${e.target.id} input`,
            label: ""
        });

       // rest of the code ....
    }

Error when test running

   TypeError: Cannot read property 'id' of undefined

      248 |             event: "",
      249 |             category: "",
    > 250 |             action: `Clicked on the ${e.target.id} input`,
      251 |             label: ""
      252 |         });
      253 |

Any help would be appreciated.

Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68

1 Answers1

1

You need to use enzyme simulate function. Simulate a click in your input test:

...

wrapper.find('input').simulate('click')
Mateus Stanki
  • 98
  • 1
  • 10
  • Dont know why, but i have to comment this line : `wrapper.find('input').props().onClick();` , in order for the `simulate` to work. – Theo Itzaris Apr 07 '19 at 18:30
  • It's because `simulate('click')` already calls onClick(). Direct call `onClick` don't inject event(your `e`) object, `simulate('click')` dispatchs an 'event' of type 'click' that in your case have a `target `('input'). – Mateus Stanki Apr 07 '19 at 22:52