React+Jest - 测试异步组件并等待安装

2024-02-23

我正在尝试测试一个具有异步功能的 React 组件componentDidMount.

Promise 本身不需要被嘲笑,它不一定用于访问外部内容,主要只是 props 的包装。

但是,为了测试它,我需要使用wrapper.update() 4 times这对我来说真的很奇怪。

解决方案在:

  • 如何使用 Jest 测试异步组件? https://stackoverflow.com/questions/46718663/how-do-test-async-components-with-jest
  • https://github.com/airbnb/enzyme/issues/1027 https://github.com/airbnb/enzyme/issues/1027
  • https://github.com/airbnb/enzyme/issues/1581 https://github.com/airbnb/enzyme/issues/1581
  • https://github.com/airbnb/enzyme/issues/346 https://github.com/airbnb/enzyme/issues/346

一切都不适合我。

这是我的测试的样子(目前有效,但这个解决方案一点也不优雅,而且可扩展性不太好):

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:'])
        })
    })
})

以下是以下的实现componentDidMount and filterResults(调用前者):

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
}

我面临着完全相同的问题。 问题是测试不会等待承诺兑现。我的解决方案是使用 Jest 提供的 did 回调来表示测试结束。

像这样:

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

    setImmediate(() => {
        expect(wrapper.find('.async').length).toBe(1);
        doneCallback();
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React+Jest - 测试异步组件并等待安装 的相关文章

随机推荐