Skip to content

Commit 3f2fc16

Browse files
authored
docs: separate API from main README.md (#70)
### Summary Separate API docs from main README.md Relates to #26. ### Test plan |README.md|api.md| |--|--| |<img width="980" alt="screenshot 2018-11-23 at 12 21 42" src="https://user-images.githubusercontent.com/5106466/48941096-740d0a80-ef1a-11e8-8c92-110f1b47826d.png">|<img width="984" alt="screenshot 2018-11-23 at 12 22 05" src="https://user-images.githubusercontent.com/5106466/48941097-740d0a80-ef1a-11e8-872b-a8dfb7814e68.png">|
1 parent 2104c48 commit 3f2fc16

File tree

2 files changed

+347
-334
lines changed

2 files changed

+347
-334
lines changed

README.md

Lines changed: 7 additions & 334 deletions
Original file line numberDiff line numberDiff line change
@@ -64,342 +64,15 @@ This library has a peerDependencies listing for `react-test-renderer` and, of co
6464

6565
As you may have noticed, it's not tied to React Native at all – you can safely use it in your React components if you feel like not interacting directly with DOM.
6666

67-
## Usage
67+
## API / Usage
6868

69-
## `render`
69+
The [public API](docs/api.md) of `react-native-testing-library` is focused around these essential methods:
7070

71-
Defined as:
72-
73-
```jsx
74-
function render(
75-
component: React.Element<*>,
76-
options?: {
77-
/* You won't often use this, but it's helpful when testing refs */
78-
createNodeMock: (element: React.Element<*>) => any,
79-
}
80-
): RenderResult {}
81-
```
82-
83-
Deeply render given React element and returns helpers to query the output.
84-
85-
```jsx
86-
import { render } from 'react-native-testing-library';
87-
88-
const { getByTestId, getByText /*...*/ } = render(<Component />);
89-
```
90-
91-
Returns a `RenderResult` object with following properties:
92-
93-
### `getByTestId: (testID: string)`
94-
95-
A method returning a `ReactTestInstance` with matching `testID` prop. Throws when no matches.
96-
97-
_Note: most methods like this one return a [`ReactTestInstance`](https://reactjs.org/docs/test-renderer.html#testinstance) with following properties that you may be interested in:_
98-
99-
```jsx
100-
type ReactTestInstance = {
101-
type: string | Function,
102-
props: { [propName: string]: any },
103-
parent: null | ReactTestInstance,
104-
children: Array<ReactTestInstance | string>,
105-
};
106-
```
107-
108-
### `getByText: (text: string | RegExp)`
109-
110-
A method returning a `ReactTestInstance` with matching text – may be a string or regular expression. Throws when no matches.
111-
112-
### `getAllByText: (text: string | RegExp)`
113-
114-
A method returning an array of `ReactTestInstance`s with matching text – may be a string or regular expression.
115-
116-
### `getByProps: (props: { [propName: string]: any })`
117-
118-
A method returning a `ReactTestInstance` with matching props object. Throws when no matches.
119-
120-
### `getAllByProps: (props: { [propName: string]: any })`
121-
122-
A method returning an array of `ReactTestInstance`s with matching props object.
123-
124-
### `getByType: (type: React.ComponentType<*>)`
125-
126-
A method returning a `ReactTestInstance` with matching a React component type. Throws when no matches.
127-
128-
### `getAllByType: (type: React.ComponentType<*>)`
129-
130-
A method returning an array of `ReactTestInstance`s with matching a React component type.
131-
132-
### `[DEPRECATED] getByName: (name: React.ComponentType<*>)`
133-
134-
A method returning a `ReactTestInstance` with matching a React component type. Throws when no matches.
135-
136-
> This method has been **deprecated** because using it results in fragile tests that may break between minor React Native versions. It will be removed in next major release (v2.0). Use [`getByType`](#getbytype-type-reactcomponenttype) instead.
137-
138-
### `[DEPRECATED] getAllByName: (name: React.ComponentType<*>)`
139-
140-
A method returning an array of `ReactTestInstance`s with matching a React component type.
141-
142-
> This method has been **deprecated** because using it results in fragile tests that may break between minor React Native versions. It will be removed in next major release (v2.0). Use [`getAllByType`](#getallbytype-type-reactcomponenttype) instead.
143-
144-
### `update: (element: React.Element<*>) => void`
145-
146-
Re-render the in-memory tree with a new root element. This simulates a React update at the root. If the new element has the same type and key as the previous element, the tree will be updated; otherwise, it will re-mount a new tree.
147-
148-
### `unmount: () => void`
149-
150-
Unmount the in-memory tree, triggering the appropriate lifecycle events
151-
152-
When using React context providers, like Redux Provider, you'll likely want to wrap rendered component with them. In such cases it's convenient to create your custom `render` method. [Follow this great guide on how to set this up](https://github.com/kentcdodds/react-testing-library#custom-render).
153-
154-
### `debug: (message?: string) => void`
155-
156-
Prints deeply rendered component passed to `render` with optional message on top. Uses [debug.deep](#debug) under the hood, but it's easier to use.
157-
158-
```jsx
159-
const { debug } = render(<Component />);
160-
161-
debug('optional message');
162-
```
163-
164-
logs optional message and colored JSX:
165-
166-
```jsx
167-
optional message
168-
169-
<TouchableOpacity
170-
activeOpacity={0.2}
171-
onPress={[Function bound fn]}
172-
>
173-
<Text>Press me</Text>
174-
</TouchableOpacity>
175-
```
176-
177-
### `debug.shallow: (message?: string) => void`
178-
179-
Prints shallowly rendered component passed to `render` with optional message on top. Uses [debug.shallow](#debug) under the hood, but it's easier to use.
180-
181-
### `toJSON: () => ?ReactTestRendererJSON`
182-
183-
Get the rendered component JSON representation, e.g. for snapshot testing.
184-
185-
## `shallow`
186-
187-
Shallowly render given React component. Since it doesn't return helpers to query the output, it's mostly advised to used for snapshot testing (short snapshots are best for code reviewers).
188-
189-
```jsx
190-
import { shallow } from 'react-native-testing-library';
191-
192-
test('Component has a structure', () => {
193-
const { output } = shallow(<Component />);
194-
expect(output).toMatchSnapshot();
195-
});
196-
```
197-
198-
## `FireEvent API`
199-
200-
### `fireEvent: (element: ReactTestInstance, eventName: string, data?: *) => void`
201-
202-
Invokes named event handler on the element or parent element in the tree.
203-
204-
```jsx
205-
import { View } from 'react-native';
206-
import { render, fireEvent } from 'react-native-testing-library';
207-
import { MyComponent } from './MyComponent';
208-
209-
const onEventMock = jest.fn();
210-
const { getByTestId } = render(
211-
<MyComponent testID="custom" onMyCustomEvent={onEventMock} />
212-
);
213-
214-
fireEvent(getByTestId('custom'), 'myCustomEvent');
215-
```
216-
217-
### `fireEvent.press: (element: ReactTestInstance) => void`
218-
219-
Invokes `press` event handler on the element or parent element in the tree.
220-
221-
```jsx
222-
import { View, Text, TouchableOpacity } from 'react-native';
223-
import { render, fireEvent } from 'react-native-testing-library';
224-
225-
const onPressMock = jest.fn();
226-
227-
const { getByTestId } = render(
228-
<View>
229-
<TouchableOpacity onPress={onPressMock} testID="button">
230-
<Text>Press me</Text>
231-
</TouchableOpacity>
232-
</View>
233-
);
234-
235-
fireEvent.press(getByTestId('button'));
236-
```
237-
238-
### `fireEvent.changeText: (element: ReactTestInstance, data?: *) => void`
239-
240-
Invokes `changeText` event handler on the element or parent element in the tree.
241-
242-
```jsx
243-
import { View, TextInput } from 'react-native';
244-
import { render, fireEvent } from 'react-native-testing-library';
245-
246-
const onChangeTextMock = jest.fn();
247-
const CHANGE_TEXT = 'content';
248-
249-
const { getByTestId } = render(
250-
<View>
251-
<TextInput testID="text-input" onChangeText={onChangeTextMock} />
252-
</View>
253-
);
254-
255-
fireEvent.changeText(getByTestId('text-input'), CHANGE_TEXT);
256-
```
257-
258-
### `fireEvent.scroll: (element: ReactTestInstance, data?: *) => void`
259-
260-
Invokes `scroll` event handler on the element or parent element in the tree.
261-
262-
```jsx
263-
import { ScrollView, TextInput } from 'react-native';
264-
import { render, fireEvent } from 'react-native-testing-library';
265-
266-
const onScrollMock = jest.fn();
267-
const eventData = {
268-
nativeEvent: {
269-
contentOffset: {
270-
y: 200,
271-
},
272-
},
273-
};
274-
275-
const { getByTestId } = render(
276-
<ScrollView testID="scroll-view" onScroll={onScrollMock}>
277-
<Text>XD</Text>
278-
</ScrollView>
279-
);
280-
281-
fireEvent.scroll(getByTestId('scroll-view'), eventData);
282-
```
283-
284-
## `waitForElement`
285-
286-
Defined as:
287-
288-
```jsx
289-
function waitForExpect<T: *>(
290-
expectation: () => T,
291-
timeout: number = 4500,
292-
interval: number = 50
293-
): Promise<T> {}
294-
```
295-
296-
Wait for non-deterministic periods of time until your element appears or times out. `waitForExpect` periodically calls `expectation` every `interval` milliseconds to determine whether the element appeared or not.
297-
298-
```jsx
299-
import { render, waitForElement } from 'react-testing-library';
300-
301-
test('waiting for an Banana to be ready', async () => {
302-
const { getByText } = render(<Banana />);
303-
304-
await waitForElement(() => getByText('Banana ready'));
305-
});
306-
```
307-
308-
If you're using Jest's [Timer Mocks](https://jestjs.io/docs/en/timer-mocks#docsNav), remember not to use `async/await` syntax as it will stall your tests.
309-
310-
## `debug`
311-
312-
Log prettified shallowly rendered component or test instance (just like snapshot) to stdout.
313-
314-
```jsx
315-
import { debug } from 'react-native-testing-library';
316-
317-
debug(<Component />);
318-
debug.shallow(<Component />); // an alias for `debug`
319-
```
320-
321-
logs:
322-
323-
```jsx
324-
<TouchableOpacity
325-
activeOpacity={0.2}
326-
onPress={[Function bound fn]}
327-
>
328-
<TextComponent
329-
text="Press me"
330-
/>
331-
</TouchableOpacity>
332-
```
333-
334-
There's also `debug.deep` that renders deeply to stdout.
335-
336-
```jsx
337-
import { debug } from 'react-native-testing-library';
338-
339-
debug.deep(<Component />);
340-
debug.deep(toJSON(), 'actually debug JSON too'); // useful when Component state changes
341-
```
342-
343-
logs:
344-
345-
```jsx
346-
<View
347-
accessible={true}
348-
isTVSelectable={true}
349-
onResponderGrant={[Function bound touchableHandleResponderGrant]}
350-
// ... more props
351-
style={
352-
Object {
353-
\\"opacity\\": 1,
354-
}
355-
}
356-
>
357-
<Text>
358-
Press me
359-
</Text>
360-
</View>
361-
```
362-
363-
Optionally you can provide a string message as a second argument to `debug`, which will be displayed right after the component.
364-
365-
## `flushMicrotasksQueue`
366-
367-
Wait for microtasks queue to flush. Useful if you want to wait for some promises with `async/await`.
368-
369-
```jsx
370-
import { flushMicrotasksQueue, render } from 'react-native-testing-library';
371-
372-
test('fetch data', async () => {
373-
const { getByText } = render(<FetchData />);
374-
getByText('fetch');
375-
await flushMicrotasksQueue();
376-
expect(getByText('fetch').props.title).toBe('loaded');
377-
});
378-
```
379-
380-
## `query` APIs
381-
382-
Each of the get APIs listed in the render section above have a complimentary query API. The get APIs will throw errors if a proper node cannot be found. This is normally the desired effect. However, if you want to make an assertion that an element is not present in the hierarchy, then you can use the query API instead:
383-
384-
```jsx
385-
import { render } from 'react-native-testing-library';
386-
387-
const { queryByText } = render(<Form />);
388-
const submitButton = queryByText('submit');
389-
expect(submitButton).toBeNull(); // it doesn't exist
390-
```
391-
392-
## `queryAll` APIs
393-
394-
Each of the query APIs have a corresponding queryAll version that always returns an Array of matching nodes. getAll is the same but throws when the array has a length of 0.
395-
396-
```jsx
397-
import { render } from 'react-native-testing-library';
398-
399-
const { queryAllByText } = render(<Forms />);
400-
const submitButtons = queryAllByText('submit');
401-
expect(submitButtons).toHaveLength(3); // expect 3 elements
402-
```
71+
- [`render`](docs/api.md#render) – deeply renders given React element and returns helpers to query the output components.
72+
- [`shallow`](docs/api.md#shallow) – shallowly renders given React component. It doesn't return any helpers to query the output.
73+
- [`fireEvent`](docs/api.md#fireevent) - invokes named event handler on the element.
74+
- [`waitForElement`](docs/api.md#waitforelement) - waits for non-deterministic periods of time until your element appears or times out.
75+
- [`flushMicrotasksQueue`](docs/api.md#flushmicrotasksqueue) - waits for microtasks queue to flush.
40376

40477
<!-- badges -->
40578

0 commit comments

Comments
 (0)