这是我有一个 react 组件的情况,它通过 componetDidUpdate 中的分页来获取所有记录。代码按预期运行,但我似乎无法让期望语句等待所有异步操作完成。
组件代码
async componentDidUpdate(prevProps) {
if (this.props !== prevProps) {
console.log('Componet did update called');
//File ids are grabbed else where and the are populating correctly
const batchSize = 50;
for (let idx = 0; idx < fileIds.length; idx += batchSize) {
const returnedFiles = await getFileVitals(fileIds.slice(idx, idx + batchSize));
this.doWork(returnedFiles, fileRefs);
this.setState({
filesToDisplay: this.files,
title: Name,
description: Description,
});
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.0/umd/react-dom.production.min.js"></script>
这是失败的 Jest 测试
//DTCQ is where the data serice is implemented
jest.unmock('../../dtcq');
beforeAll(() => {
dataReaders.getFileVitals = jest.fn();
dataReaders.getFileVitals.mockReturnValue(mockData);
});
test.only('Component renders proper number of file lines if hiding single revisions.', async () => {
console.log('Running component render proper number 30');
const component = mount(<CustomizeTemplate pkg={data.Package} files={data.Files} hideSingleRevisions featureSet={features} buildClicked={jest.fn()} />);
component.setProps({ featureSet: 'p' });
component.update();
console.log('*****Expect Processed');
// Check that there are 30 file lines, as there are more if not hiding single revisions.
await expect(component.find('file-lines').children().length).toEqual(30);
});
执行此操作的 Jest 方法是什么。我已经阅读了他们的异步文档,但没有看到任何执行此类操作的示例。
最佳答案
测试中应该有一个链接的 promise 。这与 enzyme 配合使用效果最佳 disableLifecycleMethods
option :
const component = mount(..., { disableLifecycleMethods: true });
const props = component.props();
component.setProps({ featureSet: 'p' });
await component.instance().componentDidUpdate(props);
...
关于javascript - React Jest 异步测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713499/