score:0

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 }));

score: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();
    })
})

score: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
})

score:4

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")
    })
})

Related Query

More Query from same tag