0

I have following codes, trying to test fireevent onclick but it responds an error. What is the problem?


test('fires onClick event', ()=>{     
        const onClick= jest.fn();
        const {getByTestId}=render(<App></App>)        
         fireEvent.click(getByTestId('add-board'));
         expect(onClick).toHaveBeenCalled();

})

ERROR:

  ● fires onClick event

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

    Expected number of calls: >= 1
    Received number of calls:    0

      43 |         const {getByTestId}=render(<App></App>)        
      44 |          fireEvent.click(getByTestId('add-board'));
    > 45 |          expect(onClick).toHaveBeenCalled();
         |                          ^
      46 | 
      47 | })
      48 |     

      at Object.<anonymous>.test (src/App.test.js:45:26)
ByAS
  • 21
  • 5
  • 5
    The `onClick` is not being passed to anything. Why would it be called? – evolutionxbox Oct 20 '20 at 12:26
  • what do u mean? I didnt understand @evolutionxbox – ByAS Oct 20 '20 at 12:28
  • 1
    `onClick= jest.fn()` assigns a jest mock function to the variable called "onClick". This does not mean all clicks will be listened to. It needs to be given to a component as a prop to be used. Otherwise it will do nothing. --- See https://stackoverflow.com/questions/43747397/simulate-a-button-click-in-jest – evolutionxbox Oct 20 '20 at 12:30
  • 1
    Please include the `App` component. – Sarun UK Oct 20 '20 at 17:48
  • @evolutionxbox This also doent work ```test('fires onClick event', ()=>{ const onClick= jest.fn(); const {getByTestId}=render() fireEvent.click(getByTestId('add-board')); expect(onClick).toHaveBeenCalled(1); }) ``` – ByAS Oct 20 '20 at 18:03
  • @ByAS that would only work if App _uses_ the `onClick` prop. If it doesn't then it won't do anything. – evolutionxbox Oct 20 '20 at 19:09

0 Answers0