0

I'm using Jest and Enzyme to test some React components (written using TypeScript). My old method was to use Enzyme's .simulate() function to simulate a click, but this is being deprecated in favor of using instance prop functions (i.e. just using the component's onClick() prop). However, I'm not sure how exactly to call the onClick() function directly. Below is my code:

// Get the onClick function
const buttonOnClick = wrapper.find('#diffpicker-button').first().props().onClick; 

// buttonOnClick could be a function or undefined, make sure its a function
if (!buttonOnClick) return; 

// Assignment needed here, but to what?
let event: React.MouseEvent<Element, MouseEvent>;

// How to call it?
buttonOnClick(event); 

I need to assign my event variable to pass to buttonOnClick(), but what should I assign it to? What does an onClick event actually look like? Or, am I going about this all wrong?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Royal Rat
  • 165
  • 1
  • 7
  • Do you really need an event for onClick in your component? As i see your code should be correct. If you needs an event object then you can pass an object with fields that you use in your handler) – Boykov Aug 11 '20 at 23:22
  • Also if you provide code of component and full test case(because i didn't see anything wrong) i'll can look deeply) – Boykov Aug 11 '20 at 23:23
  • https://stackoverflow.com/questions/43747397/simulate-a-button-click-in-jest – Yatrix Aug 12 '20 at 00:46
  • Does this answer your question? [Simulate a button click in Jest](https://stackoverflow.com/questions/43747397/simulate-a-button-click-in-jest) – Yatrix Aug 12 '20 at 00:46
  • @Boykov When I don't include an event, it gives an error saying that I need one. – Royal Rat Aug 13 '20 at 21:23
  • @Yatrix It doesn't quite answer my question because I can't use .simulate(), and when I just try to call the function without providing an event argument it gives an error asking for one. – Royal Rat Aug 13 '20 at 21:24
  • @user12894118 so provide one. :) – Yatrix Aug 14 '20 at 01:42
  • @Yatrix I'm not sure how. I need an event of type MouseEvent but I only know how to mock an event of type MouseEvent. And of course with TypeScript, it'll yell at me. – Royal Rat Aug 14 '20 at 04:16

1 Answers1

0

You can call onClick directly using a mock event definition like below:

// arrange
const event = {
  preventDefault: jest.fn(),
};

// act
wrapper.find("MobileLink").last().props().onClick(event);

// assert
.
.
.
  • 1
    When I do this, it gives an error: Argument of type 'MouseEvent' is not assignable to parameter of type 'MouseEvent<{}, MouseEvent>'. – Royal Rat Aug 13 '20 at 21:22
  • 1
    You might need to create the mock event as a MouseEvent: const mockEvent = new MouseEvent('click', { bubbles: true, cancelable: true, view: window, }); – Lochana Ranaweera Aug 14 '20 at 04:28