1

I have the following code and trying to test handleChange function with jest. But it seems that App.prototype is undefined. Can someone help me?

import React, {useState, useEffect} from 'react';

const App = () => {
   
    const handleChange = () => {
                   ....                
    }


return (
     <div className="btn"  data-testid='button' type="button" 
           onClick={handleChange}><span>Add</span></div>
     );
  }

Test Code

test('call handleChange function', () => {

    const spy = jest.spyOn(App.prototype, "handleChange")
    const { getByTestId } = render(<App />);
    fireEvent.click (getByTestId('button') ); 
    const button = getByTestId('button')   
    expect(spy).toHaveBeenCalled();        
})
Sarun UK
  • 6,210
  • 7
  • 23
  • 48
ByAS
  • 21
  • 5
  • App is functional component, it doesn't have prototype and handleChange cannot be reached outside it. Test effects that it causes, not handleChange itself. – Estus Flask Oct 21 '20 at 12:13
  • @EstusFlask what is the solution? – ByAS Oct 21 '20 at 12:18
  • Assert that `....` was called. – Estus Flask Oct 21 '20 at 12:53
  • What does `handleChange` do? If it calls an external function/library, you could mock out the external dependency, then assert on whether that is called and has the correct data passed to it. `handleChange` is an internal detail so I wouldn't necessarily assert on whether that is called but by the side effects produced from it. If it's making a change to the DOM, then assert on that change using RTL. Alternatively, if you must test `handleChange`, you could pass it in as a prop and spy on it. – ourmaninamsterdam Oct 29 '20 at 09:02

0 Answers0