joshwl2003
joshwl2003

Reputation: 463

React Jest Async Tests

Heres the situation I have a react component, which is grabbing all records via paging in componetDidUpdate. The code functions as intended but I can't seem to get jest expect statements to wait for all async operations to complete.

Component Code

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>

Here is the jest test that fails

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

What is jest method for doing this. I have read through their async documents and not seen any examples doing this type of operation.

Upvotes: 0

Views: 130

Answers (1)

Estus Flask
Estus Flask

Reputation: 223114

There should be a promise to chain in tests. This works best with Enzyme disableLifecycleMethods option:

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

Upvotes: 1

Related Questions