Search code examples
reactjsreact-testing-librarytesting-library

Is it okay to use the expect inside of a waitFor as my "Assert" in Act-Arrange-Assert?


I've recently begun utilizing React / DOM Testing Library in order to test all of my front-end React code. One of the first issues I've encountered is that with the way our application is laid out, I have no way of telling when loading of data (from Mock Service Worker in my case) is complete, as everything is handled via Redux/Redux Saga, and our Loading spinner component lives outside of the components which we are testing.

Due to this, in order to wait for the data to be loaded, we actually have to waitFor the raw data itself (as we can't simply await the loading spinner or text to disappear, since it lives outside of the component):

// Expect our first row's Name column to match our filter by text
await waitFor(() => expect(getTableRowAndCell(table, 1, 1).textContent).toBe('OUTSTANDING')

In this case, our assert in our Act-Arrange-Assert pattern is inside a waitFor, though there's other cases where I'm testing several rows in the table, so only the first assertion would be wrapped in the waitFor, while the others could simply be asserted directly, like so:

// Expect our first row's Value column to match our filterByText
await waitFor(() => expect(getTableRowAndCell(table, 1, 3).textContent).toBe('VALUE')
// Expect our second row's Value column to match our filterByText
expect(getTableRowAndCell(table, 2, 3).textContent).toBe('VALUE')

This leads to the topic of the question: is this a valid way to lay out assertions in my tests?


Solution

  • It's a bit of a late answer but I believe that is a perfectly fine way of writing your assertions.

    Me and other developers at my workplace have been following this blog: https://kentcdodds.com/blog/common-mistakes-with-react-testing-library

    He is the author of React Testing Library and he says it's fine to do so. Just keep in mind you should only have one assertion per waitFor