Skip to content

feature: wait for element to be removed #376

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 7 commits into from
Jun 10, 2020
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ The [public API](https://callstack.github.io/react-native-testing-library/docs/a

- [`render`](https://callstack.github.io/react-native-testing-library/docs/api#render) – deeply renders given React element and returns helpers to query the output components.
- [`fireEvent`](https://callstack.github.io/react-native-testing-library/docs/api#fireevent) - invokes named event handler on the element.
- [`waitFor`](https://callstack.github.io/react-native-testing-library/docs/api#waitfor) - waits for non-deterministic periods of time until your element appears or times out.
- [`waitFor`](https://callstack.github.io/react-native-testing-library/docs/api#waitfor) - waits for non-deterministic periods of time until queried element is added or times out.
- [`waitForElementToBeRemoved`](https://callstack.github.io/react-native-testing-library/docs/api#waitforelementtoberemoved) - waits for non-deterministic periods of time until queried element is removed or times out.
- [`within`](https://callstack.github.io/react-native-testing-library/docs/api#within) - creates a queries object scoped for given element.

## Migration Guides
Expand Down
141 changes: 141 additions & 0 deletions src/__tests__/waitForElementToBeRemoved.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// @flow
import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { render, fireEvent, waitForElementToBeRemoved } from '..';

const TestSetup = ({ shouldUseDelay = true }) => {
const [isAdded, setIsAdded] = useState(true);

const removeElement = async () => {
if (shouldUseDelay) {
setTimeout(() => setIsAdded(false), 300);
} else {
setIsAdded(false);
}
};

return (
<View>
{isAdded && <Text>Observed Element</Text>}

<TouchableOpacity onPress={removeElement}>
<Text>Remove Element</Text>
</TouchableOpacity>
</View>
);
};

test('waits when using getBy query', async () => {
const screen = render(<TestSetup />);

fireEvent.press(screen.getByText('Remove Element'));
const element = screen.getByText('Observed Element');
expect(element).toBeTruthy();

const result = await waitForElementToBeRemoved(() =>
screen.getByText('Observed Element')
);
expect(screen.queryByText('Observed Element')).toBeNull();
expect(result).toEqual(element);
});

test('waits when using getAllBy query', async () => {
const screen = render(<TestSetup />);

fireEvent.press(screen.getByText('Remove Element'));
const elements = screen.getAllByText('Observed Element');
expect(elements).toBeTruthy();

const result = await waitForElementToBeRemoved(() =>
screen.getAllByText('Observed Element')
);
expect(screen.queryByText('Observed Element')).toBeNull();
expect(result).toEqual(elements);
});

test('waits when using queryBy query', async () => {
const screen = render(<TestSetup />);

fireEvent.press(screen.getByText('Remove Element'));
const element = screen.getByText('Observed Element');
expect(element).toBeTruthy();

const result = await waitForElementToBeRemoved(() =>
screen.queryByText('Observed Element')
);
expect(screen.queryByText('Observed Element')).toBeNull();
expect(result).toEqual(element);
});

test('waits when using queryAllBy query', async () => {
const screen = render(<TestSetup />);

fireEvent.press(screen.getByText('Remove Element'));
const elements = screen.getAllByText('Observed Element');
expect(elements).toBeTruthy();

const result = await waitForElementToBeRemoved(() =>
screen.queryAllByText('Observed Element')
);
expect(screen.queryByText('Observed Element')).toBeNull();
expect(result).toEqual(elements);
});

test('checks if elements exist at start', async () => {
const screen = render(<TestSetup shouldUseDelay={false} />);

fireEvent.press(screen.getByText('Remove Element'));
expect(screen.queryByText('Observed Element')).toBeNull();

await expect(
waitForElementToBeRemoved(() => screen.queryByText('Observed Element'))
).rejects.toThrow(
'The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.'
);
});

test('waits until timeout', async () => {
const screen = render(<TestSetup />);

fireEvent.press(screen.getByText('Remove Element'));
expect(screen.getByText('Observed Element')).toBeTruthy();

await expect(
waitForElementToBeRemoved(() => screen.getByText('Observed Element'), {
timeout: 100,
})
).rejects.toThrow('Timed out in waitForElementToBeRemoved.');

// Async action ends after 300ms and we only waited 100ms, so we need to wait for the remaining
// async actions to finish
await waitForElementToBeRemoved(() => screen.getByText('Observed Element'));
});

test('waits with custom interval', async () => {
const mockFn = jest.fn(() => <View />);

try {
await waitForElementToBeRemoved(() => mockFn(), {
timeout: 400,
interval: 200,
});
} catch (e) {
// Suppress expected error
}

expect(mockFn).toHaveBeenCalledTimes(4);
});

test('works with fake timers', async () => {
jest.useFakeTimers();

const mockFn = jest.fn(() => <View />);

waitForElementToBeRemoved(() => mockFn(), {
timeout: 400,
interval: 200,
});

jest.advanceTimersByTime(400);
expect(mockFn).toHaveBeenCalledTimes(4);
});
2 changes: 2 additions & 0 deletions src/pure.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import flushMicrotasksQueue from './flushMicroTasks';
import render from './render';
import shallow from './shallow';
import waitFor, { waitForElement } from './waitFor';
import waitForElementToBeRemoved from './waitForElementToBeRemoved';
import within from './within';

export { act };
Expand All @@ -15,4 +16,5 @@ export { flushMicrotasksQueue };
export { render };
export { shallow };
export { waitFor, waitForElement };
export { waitForElementToBeRemoved };
export { within };
41 changes: 41 additions & 0 deletions src/waitForElementToBeRemoved.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// @flow
import waitFor, { type WaitForOptions } from './waitFor';
import { ErrorWithStack } from './helpers/errors';

const isRemoved = (result) =>
!result || (Array.isArray(result) && !result.length);

export default async function waitForElementToBeRemoved<T>(
expectation: () => T,
options?: WaitForOptions
): Promise<T> {
// Created here so we get a nice stacktrace
const timeoutError = new ErrorWithStack(
'Timed out in waitForElementToBeRemoved.',
waitForElementToBeRemoved
);

// Elements have to be present initally and then removed.
const initialElements = expectation();
if (isRemoved(initialElements)) {
throw new ErrorWithStack(
'The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.',
waitForElementToBeRemoved
);
}

return waitFor(() => {
let result;
try {
result = expectation();
} catch (error) {
return initialElements;
}

if (!isRemoved(result)) {
throw timeoutError;
}

return initialElements;
}, options);
}
80 changes: 66 additions & 14 deletions typings/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
fireEvent,
flushMicrotasksQueue,
waitFor,
waitForElementToBeRemoved,
act,
within,
} from '../..';
Expand Down Expand Up @@ -184,26 +185,77 @@ fireEvent.changeText(element, 'string');
fireEvent.scroll(element, 'eventData');

// waitFor API
const timeout = { timeout: 10 };
const timeoutInterval = { timeout: 100, interval: 10 };

const waitGetBy: Promise<ReactTestInstance>[] = [
waitFor<ReactTestInstance>(() => tree.getByA11yLabel('label')),
waitFor<ReactTestInstance>(() => tree.getByA11yLabel('label'), {
timeout: 10,
}),
waitFor<ReactTestInstance>(() => tree.getByA11yLabel('label'), {
timeout: 100,
interval: 10,
}),
waitFor<ReactTestInstance>(() => tree.getByA11yLabel('label'), timeout),
waitFor<ReactTestInstance>(
() => tree.getByA11yLabel('label'),
timeoutInterval
),
];

const waitGetAllBy: Promise<ReactTestInstance[]>[] = [
waitFor<ReactTestInstance[]>(() => tree.getAllByA11yLabel('label')),
waitFor<ReactTestInstance[]>(() => tree.getAllByA11yLabel('label'), {
timeout: 10,
}),
waitFor<ReactTestInstance[]>(() => tree.getAllByA11yLabel('label'), {
timeout: 100,
interval: 10,
}),
waitFor<ReactTestInstance[]>(() => tree.getAllByA11yLabel('label'), timeout),
waitFor<ReactTestInstance[]>(
() => tree.getAllByA11yLabel('label'),
timeoutInterval
),
];

// waitForElementToBeRemoved API
const waitForElementToBeRemovedGetBy: Promise<ReactTestInstance>[] = [
waitForElementToBeRemoved<ReactTestInstance>(() => tree.getByText('text')),
waitForElementToBeRemoved<ReactTestInstance>(
() => tree.getByText('text'),
timeout
),
waitForElementToBeRemoved<ReactTestInstance>(
() => tree.getByText('text'),
timeoutInterval
),
];
const waitForElementToBeRemovedGetAllBy: Promise<ReactTestInstance[]>[] = [
waitForElementToBeRemoved<ReactTestInstance[]>(() =>
tree.getAllByText('text')
),
waitForElementToBeRemoved<ReactTestInstance[]>(
() => tree.getAllByText('text'),
timeout
),
waitForElementToBeRemoved<ReactTestInstance[]>(
() => tree.getAllByText('text'),
timeoutInterval
),
];
const waitForElementToBeRemovedQueryBy: Promise<ReactTestInstance | null>[] = [
waitForElementToBeRemoved<ReactTestInstance | null>(() =>
tree.queryByText('text')
),
waitForElementToBeRemoved<ReactTestInstance | null>(
() => tree.queryByText('text'),
timeout
),
waitForElementToBeRemoved<ReactTestInstance | null>(
() => tree.queryByText('text'),
timeoutInterval
),
];
const waitForElementToBeRemovedQueryAllBy: Promise<ReactTestInstance[]>[] = [
waitForElementToBeRemoved<ReactTestInstance[]>(() =>
tree.queryAllByText('text')
),
waitForElementToBeRemoved<ReactTestInstance[]>(
() => tree.queryAllByText('text'),
timeout
),
waitForElementToBeRemoved<ReactTestInstance[]>(
() => tree.queryAllByText('text'),
timeoutInterval
),
];

const waitForFlush: Promise<any> = flushMicrotasksQueue();
Expand Down
23 changes: 16 additions & 7 deletions typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,14 @@ export type FireEventAPI = FireEventFunction & {
scroll: (element: ReactTestInstance, ...data: Array<any>) => any;
};

export declare const render: (
component: React.ReactElement<any>,
options?: RenderOptions
) => RenderAPI;

export declare const cleanup: () => void;
export declare const fireEvent: FireEventAPI;

type WaitForOptions = {
timeout?: number;
interval?: number;
Expand All @@ -290,14 +298,15 @@ export type WaitForFunction = <T = any>(
options?: WaitForOptions
) => Promise<T>;

export declare const render: (
component: React.ReactElement<any>,
options?: RenderOptions
) => RenderAPI;

export declare const cleanup: () => void;
export declare const fireEvent: FireEventAPI;
export declare const waitFor: WaitForFunction;

export type WaitForElementToBeRemovedFunction = <T = any>(
expectation: () => T,
options?: WaitForOptions
) => Promise<T>;

export declare const waitForElementToBeRemoved: WaitForElementToBeRemovedFunction;

export declare const act: (callback: () => void) => Thenable;
export declare const within: (instance: ReactTestInstance) => Queries;

Expand Down
Loading