Skip to content

Commit d557c14

Browse files
authored
Merge pull request #6 from crutchcorn/alpha-docs
Initial docs for the project
2 parents 74c8f5c + 544e8db commit d557c14

File tree

16 files changed

+1077
-77
lines changed

16 files changed

+1077
-77
lines changed

docs/api.md

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
# API
2+
3+
`CLI Testing Library`, despite taking clear inspiration from, does not re-export
4+
anything from
5+
[`DOM Testing Library`](https://testing-library.com/docs/dom-testing-library/).
6+
Likewise, while we've done our best to match the API names of
7+
[Testing Library's Core API](https://testing-library.com/docs/), because of the
8+
inherent differences between CLI apps and web apps, we're unable to match all of
9+
them.
10+
11+
> Know of a Testing Library Core API that you think would fit here that isn't
12+
> present?
13+
> [Let us know!](https://github.com/crutchcorn/cli-testing-library/issues)
14+
15+
Instead, the following API is what `CLI Testing Library` provides the following.
16+
17+
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
18+
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
19+
20+
- [`render`](#render)
21+
- [`render` Options](#render-options)
22+
- [`cwd`](#cwd)
23+
- [`spawnOpts`](#spawnopts)
24+
- [`render` Result](#render-result)
25+
- [`...queries`](#queries)
26+
- [ByText](#bytext)
27+
- [`userEvent[eventName]`](#usereventeventname)
28+
- [`debug`](#debug)
29+
- [`hasExit`](#hasexit)
30+
- [`process`](#process)
31+
- [`stdoutArr`/`stderrArr`](#stdoutarrstderrarr)
32+
- [`clear`](#clear)
33+
34+
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
35+
36+
# `render`
37+
38+
```typescript
39+
function render(
40+
command: string,
41+
args: string[],
42+
options?: {
43+
/* You won't often use this, expand below for docs on options */
44+
},
45+
): RenderResult
46+
```
47+
48+
Run the CLI application in a newly spawned process.
49+
50+
```javascript
51+
import {render} from 'cli-testing-library'
52+
53+
render('node', ['./path/to/script.js'])
54+
```
55+
56+
```javascript
57+
import {render} from 'cli-testing-library'
58+
59+
test('renders a message', () => {
60+
const {getByText} = render('node', ['./console-out.js'])
61+
expect(getByText('Hello, world!')).toBeTruthy()
62+
})
63+
```
64+
65+
# `render` Options
66+
67+
You won't often need to specify options, but if you ever do, here are the
68+
available options which you could provide as a third argument to `render`.
69+
70+
## `cwd`
71+
72+
By default, `CLI Testing Library` will run the new process in the working
73+
directory of your project's root, as defined by your testing framework. If you
74+
provide your own working directory via this option, it will change the execution
75+
directory of your process.
76+
77+
For example: If you are end-to-end testing a file moving script, you don't want
78+
to have to specify the absolute path every time. In this case, you can specify a
79+
directory as the render `cwd`.
80+
81+
```javascript
82+
const containingPath = path.resolve(__dirname, './movables')
83+
84+
const {getByText} = render('node', ['mover.js'], {
85+
cwd: containingPath,
86+
})
87+
```
88+
89+
## `spawnOpts`
90+
91+
Oftentimes, you want to modify the behavior of the spawn environment. This may
92+
include things like changing the shell that's used to run scripts or more.
93+
94+
This argument allows you to configure the options that are passed to the
95+
underlying
96+
[`child_process.spawn` NodeJS API](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options).
97+
98+
```javascript
99+
const {getByText} = render('script.ps1', {
100+
spawnOpts: {
101+
shell: 'powershell.exe',
102+
},
103+
})
104+
```
105+
106+
# `render` Result
107+
108+
The `render` method returns an object that has a few properties:
109+
110+
## `...queries`
111+
112+
The most important feature of render is that the queries from
113+
[CLI Testing Library](https://github.com/crutchcorn/cli-testing-library) are
114+
automatically returned with their first argument bound to the testInstance.
115+
116+
See [Queries](./queries.md) to learn more about how to use these queries and the
117+
philosophy behind them.
118+
119+
### ByText
120+
121+
> getByText, queryByText, findByText
122+
123+
```typescript
124+
getByText(
125+
// If you're using `screen`, then skip the container argument:
126+
instance: TestInstance,
127+
text: TextMatch,
128+
options?: {
129+
exact?: boolean = true,
130+
trim?: boolean = false,
131+
stripAnsi?: boolean = false,
132+
collapseWhitespace?: boolean = false,
133+
normalizer?: NormalizerFn,
134+
suggest?: boolean,
135+
}): TestInstance
136+
```
137+
138+
Queries for test instance `stdout` results with the given text (and it also
139+
accepts a TextMatch).
140+
141+
These options are all standard for text matching. To learn more, see our
142+
[Queries page](./queries.md).
143+
144+
## `userEvent[eventName]`
145+
146+
```javascript
147+
userEvent[eventName](...eventProps)
148+
```
149+
150+
> While `userEvent` isn't usually returned on `render` in, say,
151+
> `React Testing Library`, we're able to do so because of our differences in
152+
> implementation with upstream. See our [Differences](./differences.md) doc for
153+
> more.
154+
155+
This object is the same as described with
156+
[`userEvent` documentation](./user-event.md) with the key difference that
157+
`instance` is not expected to be passed when bound to `render`.
158+
159+
## `debug`
160+
161+
This method is a shortcut for `console.log(prettyCLI(instance)).`
162+
163+
```javascript
164+
import {render} from 'cli-testing-library'
165+
166+
const {debug} = render('command')
167+
debug()
168+
// Hello, world! How are you?
169+
//
170+
// you can also pass an instance: debug(getByText('message'))
171+
// and you can pass all the same arguments to debug as you can
172+
// to prettyCLI:
173+
// const maxLengthToPrint = 10000
174+
// debug(getByText('message'), maxLengthToPrint)
175+
```
176+
177+
This is a simple wrapper around `prettyCLI` which is also exposed and comes from
178+
[CLI Testing Library](./debug.md).
179+
180+
## `hasExit`
181+
182+
This method allows you to check if the spawned process has exit, and if so, what
183+
exit code it closed with.
184+
185+
```javascript
186+
const instance = render('command')
187+
188+
await waitFor(() => instance.hasExit()).toMatchObject({exitCode: 1})
189+
```
190+
191+
This method returns `null` if still running, but `{exitCode: number}` if it has
192+
exit
193+
194+
## `process`
195+
196+
The spawned process created by your rendered `TestInstnace`. It's a
197+
`child_instance`. This is a
198+
[regularly spawned process](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options),
199+
so you can call `process.pid` etc. to inspect the process.
200+
201+
## `stdoutArr`/`stderrArr`
202+
203+
Each of these is an array of what's output by their respective `std`\* pipe.
204+
This is used internally to create the [`debug`methods](./debug.md) and more.
205+
They're defined as:
206+
207+
```typescript
208+
interface TestInstance {
209+
stdoutArr: Array<Buffer | string>
210+
stderrArr: Array<Buffer | string>
211+
}
212+
```
213+
214+
## `clear`
215+
216+
This method acts as the terminal `clear` command might on most systems. It
217+
allows you to clear out the buffers for `stdoutArr` and `stderrArr` - even in
218+
the middle of processing - in order to do more narrowed queries.

docs/configure.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Configuration Options
2+
3+
## Introduction
4+
5+
The library can be configured via the `configure` function, which accepts:
6+
7+
- a plain JS object; this will be merged into the existing configuration. e.g.
8+
`configure({asyncUtilTimeout: 800})`
9+
- a function; the function will be given the existing configuration, and should
10+
return a plain JS object which will be merged as above, e.g.
11+
`configure(existingConfig => ({something: [...existingConfig.something, 'extra value for the something array']}))`
12+
13+
## Options
14+
15+
### `showOriginalStackTrace`
16+
17+
By default, `waitFor` will ensure that the stack trace for errors thrown by
18+
Testing Library is cleaned up and shortened so it's easier for you to identify
19+
the part of your code that resulted in the error (async stack traces are hard to
20+
debug). If you want to disable this, then set`showOriginalStackTrace` to
21+
`false`. You can also disable this for a specific call in the options you pass
22+
to `waitFor`.
23+
24+
### `throwSuggestions` (experimental)
25+
26+
When enabled, if [better queries](./queries.md) are available the
27+
test will fail and provide a suggested query to use instead. Default to `false`.
28+
29+
To disable a suggestion for a single query just add `{suggest:false}` as an
30+
option.
31+
32+
```js
33+
getByText('foo', {suggest: false}) // will not throw a suggestion
34+
```
35+
36+
### `getInstanceError`
37+
38+
A function that returns the error used when
39+
[get or find queries](./queries.md#types-of-queries) fail. Takes the error
40+
message and `TestInstance` object as arguments.
41+
42+
### `asyncUtilTimeout`
43+
44+
The global timeout value in milliseconds used by `waitFor` utilities. Defaults
45+
to 1000ms.
46+
47+
### `renderAwaitTime`
48+
49+
By default, we wait for the CLI to `spawn` the command from `render`. If we immediately resolve
50+
the promise to allow users to query, however, we lose the ability to `getByText` immediately after rendering.
51+
This [differs greatly from upstream Testing Library](./differences.md) and makes for a poor testing experience.
52+
53+
As a result, we wait this duration before resolving the promise after the process is spawned. This gives runtimes like
54+
NodeJS time to spin up and execute commands.
55+
56+
Defaults to 100ms.

docs/debug.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Debug
2+
3+
## Automatic Logging
4+
5+
When you use any `get` calls in your test cases, the current state of the
6+
`testInstance` (CLI) gets printed on the console. For example:
7+
8+
```javascript
9+
// Hello world
10+
getByText(container, 'Goodbye world') // will fail by throwing error
11+
```
12+
13+
The above test case will fail, however it prints the state of your DOM under
14+
test, so you will get to see:
15+
16+
```
17+
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.
18+
Here is the state of your container:
19+
20+
Hello world
21+
```
22+
23+
Note: Since the CLI size can get really large, you can set the limit of CLI
24+
content to be printed via environment variable `DEBUG_PRINT_LIMIT`. The default
25+
value is `7000`. You will see `...` in the console, when the CLI content is
26+
stripped off, because of the length you have set or due to default size limit.
27+
Here's how you might increase this limit when running tests:
28+
29+
```
30+
DEBUG_PRINT_LIMIT=10000 npm test
31+
```
32+
33+
This works on macOS/Linux, you'll need to do something else for Windows. If
34+
you'd like a solution that works for both, see
35+
[`cross-env`](https://www.npmjs.com/package/cross-env).
36+
37+
## `prettyCLI`
38+
39+
Built on top of [`strip-ansi`](https://github.com/chalk/strip-ansi) this helper
40+
function can be used to print out readable representation of the CLI `stdout` of
41+
a process. This can be helpful for instance when debugging tests.
42+
43+
It is defined as:
44+
45+
```typescript
46+
function prettyDOM(instance: TestInstance, maxLength?: number): string
47+
```
48+
49+
It receives the `TestInstance` to print out, an optional extra parameter to
50+
limit the size of the resulting string, for cases when it becomes too large.
51+
52+
This function is usually used alongside `console.log` to temporarily print out
53+
CLI outputs during tests for debugging purposes:
54+
55+
This function is what also powers
56+
[the automatic debugging output described above](#debugging).

0 commit comments

Comments
 (0)