Search code examples
reactjsjestjsantdreact-testing-library

the react-test-library mock click event is not working?


a simple test case : testClick.js

import React from 'react'
import { Button } from 'antd'

export default function testClick() {
  const onClick = () =>{
    console.log("2333")
  }
  return (
    <Button onClick={onClick}>testClick</Button>
  )
}

testClick.test.js

import React from 'react'
import TestClick from './testClick'
import { render, fireEvent, screen } from '@testing-library/react'
const onClick = jest.fn()
describe('partnerModal UI', () => {
  test('partnerModal UI', async () => {
    const { findByText } = await render(<TestClick />)
    const authEl = await findByText('testClick')
    await fireEvent.click(authEl)
    expect(onClick).toHaveBeenCalled()
  })
})

when i run this case , I account a error,I'm confuse that console.log has been invoke, but the on Search is not hasbeencall? why?

enter image description here


Solution

  • You created a mock onClick function but didn't pass it into the component and call it inside the onClick function. So the mock onClick function wasn't called, that's why.

    Besides, check mocked function has been called or not is testing the implementation details that is not a recommended test strategy.

    The recommended test strategy is testing the behavior of the component. When the click event happened, some state of the component may be changed, you should check what the component renders after the state changes.

    But the code you provided, onClick didn't do anything, but just called console.log to print a string. The code does not have much practical significance. The only you can do is assert console.log is to be called or not.

    import React from 'react';
    import TestClick from './testClick';
    import { render, fireEvent, screen } from '@testing-library/react';
    
    describe('partnerModal UI', () => {
      test('partnerModal UI', async () => {
        const logSpy = jest.spyOn(console, 'log');
        const { findByText } = await render(<TestClick />)
        const authEl = await findByText('testClick')
        await fireEvent.click(authEl)
        expect(logSpy).toHaveBeenCalled();
        logSpy.mockStore();
      })
    });