Testing async React Component with Jest

Mindaugas Nakrosis
1 min readSep 17, 2018

--

Hello everyone! This is my first post here, so leave me some room for improvement 😆

I have faced a problem where I wanted my Jest/Enzyme test to await for fetched data before expecting any test results.

“man walking on dock bridge near plant field during daytime” by Iswanto Arif on Unsplash

Lets say your component fetches data on componentDidMount and you have to await for the it before testing.

componentDidMount() {
this.props.store.fetchData();
}

You must make of use Promises and await for it before expect blocks in your test.

There are at least two ways how you can handle this:

  1. You can have a promise field in your store and assign value to it of data fetch.
  2. If you do not want to create additional fields in your stores, you can make use of EventEmitter:
async fetchData() {  await this.store.refresh(); //we want test to await this  eventEmitter.emit('DATA_LOADED'); }

Our test:

describe('Component test', async () => {  test('Loads data', async () => {  const dataLoadedPromise = new Promise((resolve) => {    store.eventEmitter.on('DATA_LOADED', () => resolve());  });  const wrapper = mount(profileContainer);  await dataLoadedPromise;
// expect here
});

And that’s it 😃

--

--

No responses yet