|
| 1 | +// @flow |
| 2 | +/* eslint-disable react/no-multi-comp */ |
| 3 | +import React from 'react'; |
| 4 | +import { View, Text, TouchableOpacity } from '../__mocks__/reactNativeMock'; |
| 5 | +import { render, fireEvent, waitForElement } from '..'; |
| 6 | + |
| 7 | +class Banana extends React.Component<*, *> { |
| 8 | + changeFresh = () => { |
| 9 | + this.props.onChangeFresh(); |
| 10 | + }; |
| 11 | + |
| 12 | + render() { |
| 13 | + return ( |
| 14 | + <View> |
| 15 | + {this.props.fresh && <Text testID="fresh">Fresh</Text>} |
| 16 | + <TouchableOpacity onPress={this.changeFresh} type="primary"> |
| 17 | + Change freshness! |
| 18 | + </TouchableOpacity> |
| 19 | + </View> |
| 20 | + ); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +class BananaContainer extends React.Component<*, *> { |
| 25 | + state = { fresh: false }; |
| 26 | + |
| 27 | + onChangeFresh = async () => { |
| 28 | + await new Promise(resolve => setTimeout(resolve, 300)); |
| 29 | + this.setState({ fresh: true }); |
| 30 | + }; |
| 31 | + |
| 32 | + render() { |
| 33 | + return ( |
| 34 | + <Banana onChangeFresh={this.onChangeFresh} fresh={this.state.fresh} /> |
| 35 | + ); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +test('waits for element until it stops throwing', async () => { |
| 40 | + const { getByTestId, getByName, queryByTestId } = render(<BananaContainer />); |
| 41 | + |
| 42 | + fireEvent.press(getByName('TouchableOpacity')); |
| 43 | + |
| 44 | + expect(queryByTestId('fresh')).toBeNull(); |
| 45 | + |
| 46 | + const freshBananaText = await waitForElement(() => getByTestId('fresh')); |
| 47 | + |
| 48 | + expect(freshBananaText.props.children).toBe('Fresh'); |
| 49 | +}); |
| 50 | + |
| 51 | +test('waits for element until timeout is met', async () => { |
| 52 | + const { getByTestId, getByName } = render(<BananaContainer />); |
| 53 | + |
| 54 | + fireEvent.press(getByName('TouchableOpacity')); |
| 55 | + |
| 56 | + await expect( |
| 57 | + waitForElement(() => getByTestId('fresh'), 100) |
| 58 | + ).rejects.toThrow(); |
| 59 | +}); |
| 60 | + |
| 61 | +test('waits for element with custom interval', async () => { |
| 62 | + const mockFn = jest.fn(() => { |
| 63 | + throw Error('test'); |
| 64 | + }); |
| 65 | + |
| 66 | + try { |
| 67 | + await waitForElement(() => mockFn(), 400, 200); |
| 68 | + } catch (e) { |
| 69 | + // suppress |
| 70 | + } |
| 71 | + |
| 72 | + expect(mockFn).toBeCalledTimes(3); |
| 73 | +}); |
| 74 | + |
| 75 | +test('works with fake timers', async () => { |
| 76 | + jest.useFakeTimers(); |
| 77 | + |
| 78 | + const mockFn = jest.fn(() => { |
| 79 | + throw Error('test'); |
| 80 | + }); |
| 81 | + |
| 82 | + try { |
| 83 | + waitForElement(() => mockFn(), 400, 200); |
| 84 | + } catch (e) { |
| 85 | + // suppress |
| 86 | + } |
| 87 | + jest.runTimersToTime(400); |
| 88 | + |
| 89 | + expect(mockFn).toBeCalledTimes(3); |
| 90 | + |
| 91 | + jest.useRealTimers(); |
| 92 | +}); |
0 commit comments