javascript - React Jest 异步测试

标签 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>

这是失败的 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/

相关文章:

javascript - 单击提交按钮后显示隐藏的表格

javascript - React Jest 匹配快照,使用子组件测试组件时崩溃

java - 在java程序中使用json单元测试文件

javascript - 类型错误:Users.create 不是函数

php - 如何通过 href 标签传递变量

javascript - 将数据从 HTML data-* 传递到 CKEDITOR 文本区域

reactjs - 使用 Reactjs 的侧边栏

javascript - 如何将字符串作为 props 传递并让组件像变量一样读取它?

reactjs - React Native 未调用触摸处理程序

c# - 如何正确测试抽象类