2
votes

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
Why is this test asynchronous? My first inclination is to remove the async / await keywords.Glen Carpenter
This is linter and not compiler error, so you're busy with pleasing ESLint. The first snippet is totally ok, any rules that contradict it should be disabled because they are incompatible with it. Other snippets went wrong.Estus Flask
@GlenCarpenter screen.findAllByRole("heading") returns a promise.Alfonso Tienda
@EstusFlask You're right, I think the problem is in ESLint.Alfonso Tienda

1 Answers

0
votes

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.