React Jest异步测试

时间:2018-12-10 20:54:30

标签: javascript reactjs unit-testing jestjs enzyme

在这种情况下,我有一个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>

这是开玩笑的失败测试

//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);
});

什么是开玩笑的方法。我已经阅读了他们的异步文档,没有看到任何进行此类操作的示例。

1 个答案:

答案 0 :(得分:1)

应该保证可以在测试中进行链接。这最适合与酶disableLifecycleMethods option

const component = mount(..., { disableLifecycleMethods: true });
const props = component.props();
component.setProps({ featureSet: 'p' });
await component.instance().componentDidUpdate(props);
...