React testing library fireEvent.click not working
Asked Answered
G

4

15

I am trying to basically just change a counter and show that the value has changed. I am doing this with getByTestId so that could be the problem ?

Here is my component:

import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
    const [count, setCounter] = useState(0)
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
                div
                <div
                    onClick={() => setCounter(prevCount => prevCount + 1)}
                    data-testid="addCount"
                >
                    +
                </div>
        <div data-testid="count">
          {count}
        </div>
                <div
                    onClick={() => setCounter(prevCount => prevCount - 1)}
                    data-testid="minusCount"
                >
                    -
                </div>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Here is the test I am trying to run:


describe('State is managed correctly', () => {
    const { getByTestId } = render(<App />)
    const add = getByTestId(`addCount`)
    const count = getByTestId(`count`)

    it('count starts at 0', () => {
        expect(count).toHaveTextContent("0")
    })


 it('count added, value should be 1', () => {
        fireEvent.click(add)
        expect(count).toHaveTextContent("1") // error count is still 0
    })
})
Glendon answered 11/10, 2019 at 19:50 Comment(1)
You shouldn't save state across tests like this, you're going to shoot yourself in the foot. You should run cleanup before each test run, remount the component, and manipulate the state only in the way you want to change it for that test.Grishilde
G
6

Looks like you can't really "manage" state in react-testing-library like I was hoping. Also seems like from reading the docs are you aren't supposed to either.

Here is my solution:

import React from 'react'
import { render, fireEvent, cleanup } from '@testing-library/react'

import App from '../src/App'

afterEach(cleanup)

describe('App component loads correctly', () => {
    const { container } = render(<App />)
    const { firstChild } = container
    test('renders correctly', () => {
        expect(container).toHaveTextContent(`Learn React`)
    })

    test('first child should contain class "App"', () => {
        expect(firstChild).toHaveClass(`App`)
    })
})

describe('State is managed correctly', () => {
    it('count starts at 0', () => {
        const { getByTestId } = render(<App />)
        const count = getByTestId(`count`)

        expect(count.innerHTML).toBe("0")
    })


 it('should add 1 to count', () => {
        const { getByTestId } = render(<App />)
        const count = getByTestId(`count`)
        const add = getByTestId(`addCount`)

        fireEvent.click(add)
        expect(count.innerHTML).toBe("1")
    })

    it('should minus 1 from count', () => {
        const { getByTestId } = render(<App />)
        const count = getByTestId(`count`)
        const minus = getByTestId(`minusCount`)

        fireEvent.click(minus)
        expect(count.innerHTML).toBe("-1")
    })
})
Glendon answered 11/10, 2019 at 21:53 Comment(0)
C
4

I'm using testing-library and in my case I had:

fireEvent(myElement, new MouseEvent('click'));

I added {bubbles: true} changing it to:

fireEvent(myElement, new MouseEvent('click', { bubbles: true }));

and it worked! It seems the event should bubble to work. The same happens with native dispatchEvent, need bubbles to work:

myElement.dispatchEvent(new Event("click", { bubbles: true }));
Cascio answered 19/5, 2022 at 16:36 Comment(0)
M
3

Every time you need to verify something to need to re-run the query. const count = getByTestId('count') sets count to the initial value, so you need to tell it to look up the count again after firing the event.

it('count added, value should be 1', () => {
  fireEvent.click(add)
  count = getByTestId('count')
  expect(count).toHaveTextContent("1") // error count is still 0
})
Minutia answered 11/10, 2019 at 20:56 Comment(2)
So I did expect(getByTestId('count')).toHaveTextContent("1") and now getting an error of Unable to find an element by: [data-testid="count"]Glendon
@TaylorAustin First of all need code refactor, Step 1 : <div data-testid="custom-element" /> please refer to this if you want which div or something else then you need to add data-testid for that. Step 2: Add the test case previous you mentioned Step 3: Run Test CaseSkipp
C
1
describe('State is managed correctly', () => {
const { getByTestId } = render(<App />)
const add = getByTestId(`addCount`)
const count = getByTestId(`count`)
const spy = jest.spyOn(add, 'click');
it('count starts at 0', () => {
    expect(count).toHaveTextContent("0")
})


 it('count added, value should be 1', () => {
        add.click();
        expect(count).toHaveTextContent("1") // error count is still 0
        spy.mockRestore();
    })
})
Compositor answered 6/2, 2020 at 7:4 Comment(2)
you can't use "fireEvent.click", because, you clickFn is not from propsCompositor
i tried to call the function whihc is not props as you said i did only click it got worked thanksScampi

© 2022 - 2024 — McMap. All rights reserved.