Catch problem with await in React 17, jest and testing library

Viewed 2694

I've got a problem in a test:

This is my code:

  test("should render text component", async () => {
        render(<TextComponent />)
        const headings = await screen.findAllByRole("heading")
        expect(headings.length).toBe(1)
    })

The test passes but the react compiler or lint says:

src/components/customcomponents/factory/ComponentFactory.test.jsx Line 7:9: Promise should be returned to test its fulfillment or rejection jest/valid-expect-in-promise

Ok, seems I need a catch, so:

    test("should render text component", async () => {
        render(<TextComponent />)
        const headings = await screen.findAllByRole("heading").catch(expect(false))
        expect(headings.length).toBe(1)
    })

The test passes again, but I've got a new compiler error:

src/components/customcomponents/TextComponent.test.jsx Line 8:32: findAllByRole must have await operator testing-library/await-async-query

Ok, so let's try with try...catch:

    test("should render text component", async () => {
        render(<TextComponent />)
        try {
            const headings = await screen.findAllByRole("heading")
            expect(headings.length).toBe(1)
        } catch (err) {
            expect(err).toBeTruthy()
        }
    })

The test passes... but I've got a new error!:

src/components/customcomponents/TextComponent.test.jsx Line 12:13: Avoid calling expect conditionally` jest/no-conditional-expect

So... What is the solution for this? What is the right code?

Thank you all!

1 Answers

As some people commented, I think it's a ESLint problem, there's no problem with the code but i've got some code that works and ESLint likes:

    test("should render text component", async () => {
        render(<TitleComponent />)
        let headingLength = 0;
        try {
            const headings = await screen.findAllByRole("heading")
            headingLength = headings.length
        } catch (err) { }
        expect(headingLength).toBe(1)
    })

The above code works, pass and doesn't get problems with ESLint. The drawback is that I hate let.

Related