React+Jest - Testing async components and waiting for mount

霸气de小男生 提交于 2020-01-04 05:20:13

问题


I'm trying to test a React component which has an async componentDidMount.

The promise itself doesn't need to be mocked, it's not necessarily for accessing outer content, mostly just a wrapper for props.

However, in order to test it I need to use wrapper.update() 4 times which seems really weird to me.

The solutions in:

  • How do test async components with Jest?
  • https://github.com/airbnb/enzyme/issues/1027
  • https://github.com/airbnb/enzyme/issues/1581
  • https://github.com/airbnb/enzyme/issues/346

all didn't work for me.

Here's what my test looks like (which currently works, but this solution isn't elegant at all, and not too scalable):

import * as React from 'react'
import { shallow, mount } from 'enzyme'
import LargeSelector from './LargeSelector'

describe('<LargeSelector />', async () => {
    const componentDidMountSpy = jest.spyOn(LargeSelector.prototype, 'componentDidMount')

    describe('search', async () => {
        it('should save initial response in cache', async () => {
            const wrapper = await shallow(<LargeSelector query={async (search) => ['search:' + search]} />)

            // WHY DO I NEED 4 UPDATES???
            await wrapper.update()
            await wrapper.update()
            await wrapper.update()
            await wrapper.update()

            expect(LargeSelector.prototype.componentDidMount).toHaveBeenCalledTimes(1) // works fine
            // these 2 only pass the expectation if I call wrapper.update() no less than 4 times    
            expect(wrapper.state()).toHaveProperty('options', ['search:'])
            expect(wrapper.state()).toHaveProperty('initialOptions', ['search:'])
        })
    })
})

Here are the implementations of componentDidMount and filterResults (call in the former):

public async componentDidMount() {
    if (this.props.searchOnInit) {
        const results = await this.filterResults('', [])
        if (this.props.cacheInitialResponse) {
            this.setState({ initialOptions: results })
        }
    }
}

private async filterResults(search: string, filters: IFilter[]) {
    const results = await this.props.query(search, filters)
    this.setState({ options: results })
    return results
}

回答1:


I was facing the exact same problem. The problem is that the test won't wait for the promises to be fulfilled. My solution was to use the the done callback, provided by Jest, as a signal of the test ended.

Like this:

it('wait async code before assert something', (doneCallback) => {
    const wrapper = shallow(<Component />);

    setImediate(() => {
        expect(wrapper.find('.async').length).toBe(1);
        doneCallback();
    });
});



回答2:


The weird behavior is probably because you used async for the componentDidMount implementation.

Currently, all React rendering process is synchronous, thus everything related to its rendering flow needs to be treated as synchronous. And it happens that currently too, the React team is developing a breaking change feature to allow async rendering.

But! Even after this feature is available, keep in mind that componentDidMount lifecycle hook will still be synchronous, and all the others hooks too, so it's important to be aware that React won't wait any Promise to resolve inside the hooks.

You can start a Promise inside the componentDidMount if it fits your use case, and let the resolved result change the state. But the lifecycle hook will finish before it resolves, this will affect your test case because the test will need to wait for that result of the resolved Promise to be processed before asserting it, you can use jest.runAllTicks() to guarantee this behavior.




回答3:


enzyme-async-helpers helped me a lot with this sort of problem.
You could easily get it working by adding a loading state and then doing something like:

import * as React from 'react';
import { shallow, mount } from 'enzyme';
import LargeSelector from './LargeSelector';
import { waitForState } from 'enzyme-async-helpers';

describe('<LargeSelector />', async () => {

  describe('search', async () => {
    it('should save initial response in cache', async () => {
      const wrapper = await shallow(<LargeSelector query={async (search) => ['search:' + search]} />);

      await waitForState(wrapper, state => state.loading === false);

      expect(LargeSelector.prototype.componentDidMount).toHaveBeenCalledTimes(1); 
      expect(wrapper.state()).toHaveProperty('options', ['search:']);
      expect(wrapper.state()).toHaveProperty('initialOptions', ['search:']);
    });
  });
});

And:
this.setState({ initialOptions: results })
Would have to be updated to:
this.setState({ initialOptions: results, loading: false })



来源:https://stackoverflow.com/questions/50667197/reactjest-testing-async-components-and-waiting-for-mount

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!