Skip to content

feat: waitForDomChange, waitForElement, waitForElementToBeRemoved #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 37 additions & 8 deletions projects/testing-library/src/lib/models.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { Type, DebugElement } from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';
import { Routes } from '@angular/router';
import { BoundFunction, FireObject, Queries, queries } from '@testing-library/dom';
import {
BoundFunction,
FireObject,
Queries,
queries,
waitForElement,
waitForElementToBeRemoved,
waitForDomChange,
} from '@testing-library/dom';
import { UserEvents } from './user-events';

export type RenderResultQueries<Q extends Queries = typeof queries> = { [P in keyof Q]: BoundFunction<Q[P]> };
Expand Down Expand Up @@ -34,9 +42,11 @@ export interface RenderResult<ComponentType, WrapperType = ComponentType>
detectChanges: () => void;
/**
* @description
* Re-render the same component with different props.
* The Angular `DebugElement` of the component.
*
* For more info see https://angular.io/api/core/DebugElement
*/
rerender: (componentProperties: Partial<ComponentType>) => void;
debugElement: DebugElement;
/**
* @description
* The Angular `ComponentFixture` of the component or the wrapper.
Expand All @@ -47,17 +57,36 @@ export interface RenderResult<ComponentType, WrapperType = ComponentType>
fixture: ComponentFixture<WrapperType>;
/**
* @description
* The Angular `DebugElement` of the component.
* Navigates to the href of the element or to the path.
*
* For more info see https://angular.io/api/core/DebugElement
*/
debugElement: DebugElement;
navigate: (elementOrPath: Element | string, basePath?: string) => Promise<boolean>;
/**
* @description
* Navigates to the href of the element or to the path.
* Re-render the same component with different props.
*/
rerender: (componentProperties: Partial<ComponentType>) => void;
/**
* @description
* Wait for the DOM to change.
*
* For more info see https://testing-library.com/docs/dom-testing-library/api-async#waitfordomchange
*/
navigate: (elementOrPath: Element | string, basePath?: string) => Promise<boolean>;
waitForDomChange: typeof waitForDomChange;
/**
* @description
* Wait for DOM elements to appear, disappear, or change.
*
* For more info see https://testing-library.com/docs/dom-testing-library/api-async#waitforelement
*/
waitForElement: typeof waitForElement;
/**
* @description
* Wait for the removal of element(s) from the DOM.
*
* For more info see https://testing-library.com/docs/dom-testing-library/api-async#waitforelementtoberemoved
*/
waitForElementToBeRemoved: typeof waitForElementToBeRemoved;
}

export interface RenderComponentOptions<ComponentType, Q extends Queries = typeof queries> {
Expand Down
53 changes: 52 additions & 1 deletion projects/testing-library/src/lib/testing-library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@ import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule, NoopAnimationsModule } from '@angular/platform-browser/animations';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { fireEvent, FireFunction, FireObject, getQueriesForElement, prettyDOM } from '@testing-library/dom';
import {
fireEvent,
FireFunction,
FireObject,
getQueriesForElement,
prettyDOM,
waitForDomChange,
waitForElement,
waitForElementToBeRemoved,
} from '@testing-library/dom';
import { RenderComponentOptions, RenderDirectiveOptions, RenderResult } from './models';
import { createSelectOptions, createType } from './user-events';

Expand Down Expand Up @@ -111,6 +120,45 @@ export async function render<SutType, WrapperType = SutType>(
return result;
};

function componentWaitForDomChange<Result>(options?: {
container?: HTMLElement;
timeout?: number;
mutationObserverOptions?: MutationObserverInit;
}): Promise<Result> {
const interval = setInterval(detectChanges, 10);
return waitForDomChange<Result>({ container: fixture.nativeElement, ...options }).finally(() =>
clearInterval(interval),
);
}

function componentWaitForElement<Result>(
callback: () => Result,
options?: {
container?: HTMLElement;
timeout?: number;
mutationObserverOptions?: MutationObserverInit;
},
): Promise<Result> {
const interval = setInterval(detectChanges, 10);
return waitForElement(callback, { container: fixture.nativeElement, ...options }).finally(() =>
clearInterval(interval),
);
}

function componentWaitForElementToBeRemoved<Result>(
callback: () => Result,
options?: {
container?: HTMLElement;
timeout?: number;
mutationObserverOptions?: MutationObserverInit;
},
): Promise<Result> {
const interval = setInterval(detectChanges, 10);
return waitForElementToBeRemoved(callback, { container: fixture.nativeElement, ...options }).finally(() =>
clearInterval(interval),
);
}

return {
fixture,
detectChanges,
Expand All @@ -121,6 +169,9 @@ export async function render<SutType, WrapperType = SutType>(
debug: (element = fixture.nativeElement) => console.log(prettyDOM(element)),
type: createType(eventsWithDetectChanges),
selectOptions: createSelectOptions(eventsWithDetectChanges),
waitForDomChange: componentWaitForDomChange,
waitForElement: componentWaitForElement,
waitForElementToBeRemoved: componentWaitForElementToBeRemoved,
...getQueriesForElement(fixture.nativeElement, queries),
...eventsWithDetectChanges,
};
Expand Down
40 changes: 40 additions & 0 deletions projects/testing-library/tests/wait-for-dom-change.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Component, OnInit } from '@angular/core';
import { render } from '../src/public_api';
import { timer } from 'rxjs';

@Component({
selector: 'fixture',
template: `
<div *ngIf="oneVisible" data-testid="block-one">One</div>
<div *ngIf="twoVisible" data-testid="block-two">Two</div>
`,
})
class FixtureComponent implements OnInit {
oneVisible = false;
twoVisible = false;

ngOnInit() {
timer(200).subscribe(() => (this.oneVisible = true));
timer(400).subscribe(() => (this.twoVisible = true));
}
}

test('waits for the DOM to change', async () => {
const { queryByTestId, getByTestId, waitForDomChange } = await render(FixtureComponent);

await waitForDomChange();

getByTestId('block-one');
expect(queryByTestId('block-two')).toBeNull();

await waitForDomChange();

getByTestId('block-one');
getByTestId('block-two');
});

test('allows to override options', async () => {
const { waitForDomChange } = await render(FixtureComponent);

await expect(waitForDomChange({ timeout: 100 })).rejects.toThrow(/Timed out in waitForDomChange/i);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Component, OnInit } from '@angular/core';
import { render } from '../src/public_api';
import { timer } from 'rxjs';

@Component({
selector: 'fixture',
template: `
<div *ngIf="visible" data-testid="im-here">👋</div>
`,
})
class FixtureComponent implements OnInit {
visible = true;
ngOnInit() {
timer(500).subscribe(() => (this.visible = false));
}
}

test('waits for element to be removed', async () => {
const { queryByTestId, getByTestId, waitForElementToBeRemoved } = await render(FixtureComponent);

await waitForElementToBeRemoved(() => getByTestId('im-here'));

expect(queryByTestId('im-here')).toBeNull();
});

test('allows to override options', async () => {
const { getByTestId, waitForElementToBeRemoved } = await render(FixtureComponent);

await expect(waitForElementToBeRemoved(() => getByTestId('im-here'), { timeout: 200 })).rejects.toThrow(
/Timed out in waitForElementToBeRemoved/i,
);
});
37 changes: 37 additions & 0 deletions projects/testing-library/tests/wait-for-element.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Component } from '@angular/core';
import { render } from '../src/public_api';
import { timer } from 'rxjs';

@Component({
selector: 'fixture',
template: `
<button data-testid="button" (click)="load()">Load</button>
<div>{{ result }}</div>
`,
})
class FixtureComponent {
result = '';

load() {
timer(500).subscribe(() => (this.result = 'Success'));
}
}

test('waits for element to be visible', async () => {
const { getByTestId, click, waitForElement, getByText } = await render(FixtureComponent);

click(getByTestId('button'));

await waitForElement(() => getByText('Success'));
getByText('Success');
});

test('allows to override options', async () => {
const { getByTestId, click, waitForElement, getByText } = await render(FixtureComponent);

click(getByTestId('button'));

await expect(waitForElement(() => getByText('Success'), { timeout: 200 })).rejects.toThrow(
/Unable to find an element with the text: Success/i,
);
});
2 changes: 1 addition & 1 deletion projects/testing-library/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"experimentalDecorators": true,
"importHelpers": true,
"types": [],
"lib": ["dom", "es2015"]
"lib": ["dom", "es2015", "es2018.promise"]
},
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
Expand Down