diff --git a/src/tester.tsx b/src/tester.tsx index 3a4a87a..663e6eb 100644 --- a/src/tester.tsx +++ b/src/tester.tsx @@ -1,6 +1,7 @@ import React, { Fragment } from 'react'; import { + flushPromises, getInstance, getValue, isString, @@ -200,9 +201,14 @@ class Tester { this.createShallowWrapper(); } - if (mountOpts.async) { - await this.sleep(); - this.update(); + if (mountOpts.async !== false) { + if (this.instance) { + await this.instance.componentDidMount(); + } + + // See https://github.com/enzymejs/enzyme/issues/1587 + await flushPromises(); + await this.refresh(); } return this; diff --git a/src/utils.ts b/src/utils.ts index a09b4a2..6f28e76 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -4,7 +4,7 @@ export function getInstance (component: any) { const instance = component.instance(); - return instance.wrappedInstance || instance; + return instance && (instance.wrappedInstance || instance); } export function getValue (tester: any, value: unknown) { @@ -22,3 +22,7 @@ export function capitalize (string: string) { export function isString (value: unknown): value is string { return typeof value === 'string' || value instanceof String; } + +export async function flushPromises () { + return new Promise((resolve, _reject) => setImmediate(resolve)); +} diff --git a/test/tester.test.tsx b/test/tester.test.tsx index a6b5338..dc7b842 100644 --- a/test/tester.test.tsx +++ b/test/tester.test.tsx @@ -1,13 +1,35 @@ /* global it, describe, expect */ -import React from 'react'; +import React, { Component } from 'react'; import { Tester } from '../src'; +import { sleep } from '../src/utils'; const COMPONENT_ID = 'testing-component'; const MyTestingComponent = (props: any) =>
; -describe('Tester', () => { +class AsyncComponent extends Component { + public constructor (props: object) { + super(props); + this.state = { status: 'loading' }; + } + + public async componentDidMount () { + await sleep(10); + this.setState({ + status: 'done', + }); + } + public render () { + return ( +
+ {this.state.status} +
+ ); + } +} + +describe('Tester', () => { it('Init tests', async () => { const tester = await new Tester(MyTestingComponent).mount(); expect(tester.wrapper).toBeTruthy(); @@ -19,4 +41,10 @@ describe('Tester', () => { expect(tester.wrapper).toBeTruthy(); expect(tester.wrapper.html()).toContain('test-hook-component'); }); + + it('Awaits async componentDidMount', async () => { + const tester = await new Tester(AsyncComponent).mount(); + expect(tester.text()).toContain('done'); + }); + });