我正在尝试测试一个具有异步功能的 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
}