Pratheep
Pratheep

Reputation: 1076

Testing React component that fetches data asynchronously

I'm fairly new to testing-library, and trying to figure out how to write some tests for a component that fetches data asynchronously.

Here is the codesandbox.

I'm having a hard time figuring out the best way to do it with testing-library. Especially since it involves fetching data asynchronously and there is debounce.

The assertion I'm trying to make is fairly simple(you can see it in the test file) and it'll be great if someone could help me figure this out.

Thanks.

Upvotes: 0

Views: 105

Answers (1)

Gio Polvara
Gio Polvara

Reputation: 26978

In this post I explain how to deal with API calls in RTL.

As for the debounce I suggest you just mock it out so that it doesn't run in your tests:

jest.mock('lodash/debounce', () => fn => fn)

Or if you want something a bit more complete:

jest.mock('lodash/debounce', () => fn => {
  const debounced = function(...args) {
    const context = this
    return fn.apply(context, args)
   }
   debounced.cancel = () => {}
   return debounced
})

Upvotes: 1

Related Questions