Skip to content
This repository was archived by the owner on Aug 1, 2020. It is now read-only.

Commit 77f3014

Browse files
committed
fix formatting of API docs
1 parent fd61aa6 commit 77f3014

17 files changed

+1591
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
id: version-3.0.0-api-act
3+
title: Act
4+
sidebar_label: Act
5+
original_id: api-act
6+
---
7+
8+
## `act`
9+
10+
This is a light wrapper around the
11+
[`react-test-renderer` `act` function](https://reactjs.org/docs/test-renderer.html).
12+
All it does is forward all arguments to the act function if your version of
13+
react supports `act`.
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
---
2+
id: version-3.0.0-api-async
3+
title: Async Utilities
4+
sidebar_label: Async Utilities
5+
original_id: api-async
6+
---
7+
8+
Several utilities are provided for dealing with asynchronous code. These can be useful to wait for
9+
an element to appear or disappear in response to an action. (See the
10+
[guide to testing disappearance](guide-disappearance.md).)
11+
12+
## `wait`
13+
14+
```typescript
15+
function wait(
16+
callback?: () => void,
17+
options?: {
18+
timeout?: number;
19+
interval?: number;
20+
},
21+
): Promise<void>;
22+
```
23+
24+
When in need to wait for non-deterministic periods of time you can use `wait`, to wait for your
25+
expectations to pass. The `wait` function is a small wrapper around the
26+
[`wait-for-expect`](https://github.com/TheBrainFamily/wait-for-expect) module. Here's a simple
27+
example:
28+
29+
```javascript
30+
await wait(() => getByLabelText('username'));
31+
getByLabelText('username').value = 'chucknorris';
32+
```
33+
34+
This can be useful if you have a unit test that mocks API calls and you need to wait for your mock
35+
promises to all resolve.
36+
37+
The default `callback` is a no-op function (used like `await wait()`). This can be helpful if you
38+
only need to wait for one tick of the event loop (in the case of mocked API calls with promises that
39+
resolve immediately).
40+
41+
The default `timeout` is `4500ms` which will keep you under
42+
[Jest's default timeout of `5000ms`](https://facebook.github.io/jest/docs/en/jest-object.html#jestsettimeouttimeout).
43+
44+
The default `interval` is `50ms`. However it will run your callback immediately on the next tick of
45+
the event loop (in a `setTimeout`) before starting the intervals.
46+
47+
## `waitForElement`
48+
49+
```typescript
50+
function waitForElement<T>(
51+
callback: () => T,
52+
options?: {
53+
timeout?: number;
54+
interval?: number;
55+
},
56+
): Promise<T>;
57+
```
58+
59+
When you need to wait for elements to appear, you can use `waitForElement`. The `waitForElement`
60+
function is a similar to `wait`, but is specifically intended to wait for an element to appear.
61+
Additionally, the result is returned for you to use.
62+
63+
Here's a simple example:
64+
65+
```javascript
66+
const usernameElement = await waitForElement(() => getByLabelText('username'));
67+
expect(usernameElement).toHaveTextContent('chucknorris');
68+
```
69+
70+
You can also wait for multiple elements at once:
71+
72+
```javascript
73+
const [usernameElement, passwordElement] = await waitForElement(() => [
74+
getByLabelText('username'),
75+
getByLabelText('password'),
76+
]);
77+
```
78+
79+
The default `timeout` is `4500ms` which will keep you under
80+
[Jest's default timeout of `5000ms`](https://facebook.github.io/jest/docs/en/jest-object.html#jestsettimeouttimeout).
81+
82+
The default `interval` is `50ms`. However it will run your callback immediately on the next tick of
83+
the event loop (in a `setTimeout`) before starting the intervals.
84+
85+
## `waitForElementToBeRemoved`
86+
87+
```typescript
88+
function waitForElementToBeRemoved<T>(
89+
callback: () => T,
90+
options?: {
91+
timeout?: number;
92+
interval?: number;
93+
},
94+
): Promise<T>;
95+
```
96+
97+
When you need to wait for elements to be removed, or you can use `waitForElementToBeRemoved`. The
98+
`waitForElementToBeRemoved` function is a similar to `wait`, but is a helper specifically intended
99+
to wait for an element to be removed from the tree. Similarly to `waitForElement` the result of the
100+
callback is returned as a Promise, but in most cases you won't need it.
101+
102+
Here's a simple example:
103+
104+
```javascript
105+
await waitForElementToBeRemoved(() => queryAllByLabelText('list-item'));
106+
```
107+
108+
The default `timeout` is `4500ms` which will keep you under
109+
[Jest's default timeout of `5000ms`](https://facebook.github.io/jest/docs/en/jest-object.html#jestsettimeouttimeout).
110+
111+
The default `interval` is `50ms`. However it will run your callback immediately on the next tick of
112+
the event loop (in a `setTimeout`) before starting the intervals.
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
id: version-3.0.0-api-events
3+
title: Firing Events
4+
sidebar_label: Firing Events
5+
original_id: api-events
6+
---
7+
8+
## Basic example
9+
10+
```javascript
11+
import { fireEvent, NativeTestEvent, render } from 'native-testing-library';
12+
13+
const { getByText } = render(<Button title="Submit" />);
14+
fireEvent(getByText(container, 'Submit'), new NativeTestEvent('press'));
15+
```
16+
17+
## `fireEvent[eventName]`
18+
19+
```typescript
20+
fireEvent[eventName](node: FiberRoot, eventProperties: NativeTestEvent)
21+
```
22+
23+
Convenience methods for firing events. Check out
24+
[src/events.js](https://github.com/testing-library/native-testing-library/blob/master/src/events.js)
25+
for a full list as well as `validTargets` for every event type.
26+
27+
```javascript
28+
import { fireEvent, render } from 'native-testing-library';
29+
30+
const { getByText } = render(<Button title="Submit" />);
31+
fireEvent.press(getByText('Submit'));
32+
```
33+
34+
**nativeEvent**: React Native tends to put everything relevant to their built-in events on an object
35+
called nativeEvent. When you fire an event using this library, you will have to build a mock event
36+
config. You will use this particularly for events like a change event:
37+
38+
```javascript
39+
fireEvent.change(getByLabelText(/username/i), { nativeEvent: { text: 'a' } });
40+
```
41+
42+
**changeText**: `Text` has a method for value updating called `onChangeText`. Since this is such a
43+
commonly used method, there is a special case in the library for this method.
44+
45+
```javascript
46+
fireEvent.changeText(getByLabelText(/username/i), 'a');
47+
```
48+
49+
**customEvent**: You may be using a library that has custom event listeners that you want to be able
50+
to fire. This is how you would fire one of these events:
51+
52+
```javascript
53+
fireEvent(
54+
getByTestId('swiper'),
55+
new NativeTestEvent('myEvent', { nativeEvent: { value: 'testing' } }),
56+
);
57+
```
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
---
2+
id: version-3.0.0-api-helpers
3+
title: Helpers
4+
sidebar_label: Helpers
5+
original_id: api-helpers
6+
---
7+
8+
## Custom Queries
9+
10+
`native-testing-library` exposes some of the helper functions that are used to implement the default
11+
queries. You can use the helpers to build custom queries. For example, the code below shows a way to
12+
query your TestInstance by a `style` prop. Note: test files would need to now import `test-utils.js`
13+
instead of using `native-testing-library` directly. Also note, please never actually implement this
14+
helper, it's just an example of what's possible.
15+
16+
```javascript
17+
// test-utils.js
18+
import * as nativeTestingLib from 'native-testing-library';
19+
20+
const { queryHelpers } = nativeTestingLib;
21+
22+
export const queryByStyle = queryHelpers.queryByProp.bind(null, 'style');
23+
export const queryAllByStyle = queryHelpers.queryByProp.bind(null, 'style');
24+
25+
export function getAllByStyle(container, styles, ...rest) {
26+
const els = queryAllByStyle(container, styles, ...rest);
27+
if (!els.length) {
28+
throw getElementError(`Unable to find an element by style="${styles}"`, container);
29+
}
30+
return els;
31+
}
32+
33+
export function getByStyle(...args) {
34+
return queryHelpers.firstResultOrNull(getAllByStyle, ...args);
35+
}
36+
37+
// re-export with overrides
38+
export {
39+
...nativeTestingLib,
40+
getByStyle,
41+
getAllByStyle,
42+
queryByStyle,
43+
queryAllByStyle,
44+
};
45+
```
46+
47+
> **Note**
48+
>
49+
> Custom queries can be added to the `render` method by adding `queries` to the options config
50+
> object. See the render [options](/docs/api-render#render-options).
51+
52+
## `getNodeText`
53+
54+
```typescript
55+
getNodeText(node: React.ReactElement<any>)
56+
```
57+
58+
Returns the complete text content of an element, removing any extra whitespace, and joining children
59+
that are an array. The intention is to treat text in nodes exactly as how it is perceived by users
60+
in a browser, where any extra whitespace within words in the html code is not meaningful when the
61+
text is rendered, and all text appears as one cohesive string regardless of the code.
62+
63+
```javascript
64+
getNodeText(
65+
<Text>
66+
{`
67+
Hello
68+
World !
69+
`}
70+
</Text>,
71+
); // "Hello World !"
72+
```
73+
74+
## `within` and `getQueriesForElement` APIs
75+
76+
`within` (an alias to `getQueriesForElement`) takes a `NativeTestInstance` and binds it to the raw
77+
query functions, allowing them to be used without manually specifying a container.
78+
79+
Example: To get the username input of a login form within a `<LoginModal />`, you could do:
80+
81+
```js
82+
import { render, within } from 'native-testing-library';
83+
84+
const { getByLabelText } = render(<LoginModal />);
85+
const loginForm = getByLabelText('login-form');
86+
87+
within(loginForm).getByPlaceholderText('Username');
88+
```
89+
90+
## Debugging
91+
92+
When you use any `get` calls in your test cases, the current contents of the `baseElement` get
93+
printed on the console. For example:
94+
95+
```javascript
96+
// <Text>Hello world</Text>
97+
getByText('Goodbye world'); // will fail by throwing error
98+
```
99+
100+
The above test case will fail, however it prints the state of your React tree being tested, so you
101+
will get to see:
102+
103+
```
104+
Unable to find an element with the text: Goodbye world. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
105+
Here is the state of your container:
106+
<Text>
107+
Hello World!
108+
</Text>
109+
```
110+
111+
Note: Since the debug size can get really large, you can set the limit of debug content to be
112+
printed via environment variable `DEBUG_PRINT_LIMIT`. The default value is `7000`. You will see
113+
`...` in the console, when the debug content is stripped off, because of the length you have set or
114+
due to default size limit. Here's how you might increase this limit when running tests:
115+
116+
```
117+
DEBUG_PRINT_LIMIT=10000 npm test
118+
```
119+
120+
This works on macOS/linux, you'll need to do something else for windows. If you'd like a solution
121+
that works for both, see [`cross-env`](https://www.npmjs.com/package/cross-env)
122+
123+
### `prettyPrint`
124+
125+
This helper function can be used to print out readable representation of the React tree of a node.
126+
This can be helpful for instance when debugging tests.
127+
128+
It is defined as:
129+
130+
```typescript
131+
function prettyPrint(node: React.ReactElement<any>, maxLength?: number): string;
132+
```
133+
134+
It receives the root node to print out, and an optional extra argument to limit the size of the
135+
resulting string, for cases when it becomes too large.
136+
137+
This function is usually used alongside `console.log` to temporarily print out React trees during
138+
tests for debugging purposes:
139+
140+
```javascript
141+
console.log(
142+
prettyPrint(
143+
<View>
144+
<Text>hi</Text>
145+
</View>,
146+
),
147+
);
148+
// <View>
149+
// <Text>
150+
// Hi
151+
// </Text>
152+
// </View>
153+
```
154+
155+
This function is what also powers [the automatic debugging output described above](#debugging).

0 commit comments

Comments
 (0)