Skip to content

Commit

Permalink
fix(types): generate declaration files instead of importing from src (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jgoux authored Feb 16, 2023
1 parent a716216 commit 4e77f64
Show file tree
Hide file tree
Showing 23 changed files with 132 additions and 35 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ practices.</p>
[![Code of Conduct](https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square)](./CODE_OF_CONDUCT.md)

<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->

[![All Contributors](https://img.shields.io/badge/all_contributors-5-orange.svg?style=flat-square)](#contributors-)

<!-- ALL-CONTRIBUTORS-BADGE:END -->

[![Watch on GitHub](https://img.shields.io/github/watchers/crutchcorn/cli-testing-library.svg?style=social)](https://github.com/crutchcorn/cli-testing-library/watchers)
Expand Down
6 changes: 3 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ exit code it closed with.
```javascript
const instance = render('command')
await waitFor(() => expect(instance.hasExit()).toMatchObject({ exitCode: 1 }))
await waitFor(() => expect(instance.hasExit()).toMatchObject({exitCode: 1}))
```

This method returns `null` if still running, but `{exitCode: number}` if it has
Expand All @@ -206,8 +206,8 @@ They're defined as:

```typescript
interface TestInstance {
stdoutArr: Array<{contents: Buffer | string, timestamp: number}>
stderrArr: Array<{contents: Buffer | string, timestamp: number}>
stdoutArr: Array<{contents: Buffer | string; timestamp: number}>
stderrArr: Array<{contents: Buffer | string; timestamp: number}>
}
```

Expand Down
6 changes: 3 additions & 3 deletions src/__tests__/execute-scripts/log-err.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
console.log("Log here");
console.warn("Warn here");
console.error("Error here");
console.log('Log here')
console.warn('Warn here')
console.error('Error here')
10 changes: 4 additions & 6 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,15 @@ let config: InternalConfig = {

// called when getBy* queries fail. (message, container) => Error
getInstanceError(message, testInstance: TestInstance | undefined) {
let instanceWarning: string = "";
let instanceWarning: string = ''
if (testInstance) {
const stdallArrStr = testInstance.getStdallStr();
const stdallArrStr = testInstance.getStdallStr()
instanceWarning = `\n${stdallArrStr}`
} else {
instanceWarning = "";
instanceWarning = ''
}
const error = new Error(
[message, instanceWarning]
.filter(Boolean)
.join('\n\n'),
[message, instanceWarning].filter(Boolean).join('\n\n'),
)
error.name = 'TestingLibraryElementError'
return error
Expand Down
5 changes: 4 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import {cleanup} from './pure'
// or teardown then we'll automatically run cleanup afterEach test
// this ensures that tests run in isolation from each other
// if you don't like this then set the CTL_SKIP_AUTO_CLEANUP env variable to 'true'.
if (typeof process === 'undefined' || !(process.env && process.env.CTL_SKIP_AUTO_CLEANUP)) {
if (
typeof process === 'undefined' ||
!(process.env && process.env.CTL_SKIP_AUTO_CLEANUP)
) {
// ignore teardown() in code coverage because Jest does not support it
/* istanbul ignore else */
if (typeof afterEach === 'function') {
Expand Down
4 changes: 3 additions & 1 deletion src/matchers/to-be-in-the-console.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ export function toBeInTheConsole(instance) {
}

const errormessage = instance
? getDefaultNormalizer()(instance.stdoutArr.map(obj => obj.contents).join('\n'))
? getDefaultNormalizer()(
instance.stdoutArr.map(obj => obj.contents).join('\n'),
)
: null

return {
Expand Down
4 changes: 3 additions & 1 deletion src/matchers/to-have-errormessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ export function toHaveErrorMessage(testInstance, checkWith) {

const expectsErrorMessage = checkWith !== undefined

const errormessage = getDefaultNormalizer()(testInstance.stderrArr.map(obj => obj.contents).join('\n'))
const errormessage = getDefaultNormalizer()(
testInstance.stderrArr.map(obj => obj.contents).join('\n'),
)

return {
pass: expectsErrorMessage
Expand Down
2 changes: 1 addition & 1 deletion src/pretty-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function prettyCLI(testInstance, maxLength) {
throw new TypeError(`Expected an instance but got ${testInstance}`)
}

const outStr = testInstance.getStdallStr();
const outStr = testInstance.getStdallStr()

// eslint-disable-next-line no-negated-condition
return maxLength !== undefined && outStr.length > maxLength
Expand Down
26 changes: 16 additions & 10 deletions src/pure.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import childProcess from 'child_process'
import {performance} from 'perf_hooks'
import stripFinalNewline from 'strip-final-newline'
import {RenderOptions, RenderResult, TestInstance} from '../types/pure'
import {_runObservers} from './mutation-observer'
Expand All @@ -8,7 +9,6 @@ import {bindObjectFnsToInstance, setCurrentInstance} from './helpers'
import {fireEvent} from './events'
import {getConfig} from './config'
import {logCLI} from './pretty-cli'
import {performance} from 'perf_hooks'

const mountedInstances = new Set<TestInstance>()

Expand Down Expand Up @@ -48,8 +48,8 @@ async function render(
},
// An array of strings gathered from stdout when unable to do
// `await stdout` because of inquirer interactive prompts
stdoutArr: [] as Array<{contents: Buffer | string, timestamp: number}>,
stderrArr: [] as Array<{contents: Buffer | string, timestamp: number}>,
stdoutArr: [] as Array<{contents: Buffer | string; timestamp: number}>,
stderrArr: [] as Array<{contents: Buffer | string; timestamp: number}>,
hasExit() {
return this.__exitCode === null ? null : {exitCode: this.__exitCode}
},
Expand All @@ -66,7 +66,10 @@ async function render(
}

const resStr = stripFinalNewline(result as string)
execOutputAPI.stdoutArr.push({contents: resStr, timestamp: performance.now()})
execOutputAPI.stdoutArr.push({
contents: resStr,
timestamp: performance.now(),
})
_runObservers()
})

Expand All @@ -77,7 +80,10 @@ async function render(
}

const resStr = stripFinalNewline(result as string)
execOutputAPI.stderrArr.push({contents: resStr, timestamp: performance.now()})
execOutputAPI.stderrArr.push({
contents: resStr,
timestamp: performance.now(),
})
_runObservers()
})

Expand All @@ -104,12 +110,12 @@ async function render(

await execOutputAPI._isReady


function getStdallStr(this: Omit<TestInstance, 'getStdallStr'>) {
return this.stderrArr.concat(this.stdoutArr)
.sort((a,b) => a.timestamp < b.timestamp ? -1 : 1)
.map(obj => obj.contents)
.join('\n');
return this.stderrArr
.concat(this.stdoutArr)
.sort((a, b) => (a.timestamp < b.timestamp ? -1 : 1))
.map(obj => obj.contents)
.join('\n')
}

return Object.assign(
Expand Down
4 changes: 3 additions & 1 deletion src/suggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ function canSuggest(currentMethod, requestedMethod, data) {
}

export function getSuggestedQuery(instance, variant = 'get', method) {
const textContent = normalize(instance.stdoutArr.map(obj => obj.contents).join('\n'))
const textContent = normalize(
instance.stdoutArr.map(obj => obj.contents).join('\n'),
)
if (canSuggest('Text', method, textContent)) {
return makeSuggestion('Text', instance, textContent, {variant})
}
Expand Down
2 changes: 1 addition & 1 deletion tests/setup-env.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import '../src/extend-expect'
import {configure, getConfig} from '../src/config'
import hasAnsi from 'has-ansi'
import stripAnsi from 'strip-ansi'
import {configure, getConfig} from '../src/config'

/**
* We have instances where we need to disable this serializer to test for ANSI codes
Expand Down
4 changes: 2 additions & 2 deletions types/__tests__/type-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ export async function eventTest() {
export async function keyboardTest() {
const instance = await render('command', [])

userEvent.keyboard(instance, 'Test')
instance.userEvent.keyboard('Test')
await userEvent.keyboard(instance, 'Test')
await instance.userEvent.keyboard('Test')
await instance.userEvent.keyboard('Test', {delay: 0})

fireEvent.write(instance, {value: 'test'})
Expand Down
12 changes: 12 additions & 0 deletions types/event-map.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {TestInstance} from '../types'
declare const eventMap: {
sigterm: (instance: TestInstance) => Promise<void>
sigkill: (instance: TestInstance) => Promise<void>
write: (
instance: TestInstance,
props: {
value: string
},
) => boolean
}
export {eventMap}
2 changes: 1 addition & 1 deletion types/events.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {eventMap} from '../src/event-map'
import type {eventMap} from './event-map'
import {TestInstance} from './pure'

type EventMap = typeof eventMap
Expand Down
2 changes: 1 addition & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ export * from './queries'
export * from './query-helpers'
export * from './suggestions'
export * from './wait-for'
export * from '../src/user-event/index'
export * from './user-event/index'
6 changes: 3 additions & 3 deletions types/pure.d.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import type {SpawnOptionsWithoutStdio} from 'child_process'
import {ChildProcessWithoutNullStreams} from 'child_process'
import type userEvent from '../src/user-event/index'
import type userEvent from './user-event/index'
import * as queries from './queries'
import type {BoundFunction} from './get-queries-for-instance'

export interface TestInstance {
clear(): void
process: ChildProcessWithoutNullStreams
stdoutArr: Array<{contents: Buffer | string, timestamp: number}>
stderrArr: Array<{contents: Buffer | string, timestamp: number}>
stdoutArr: Array<{contents: Buffer | string; timestamp: number}>
stderrArr: Array<{contents: Buffer | string; timestamp: number}>
getStdallStr(): string
hasExit(): null | {exitCode: number}
debug(maxLength?: number): void
Expand Down
6 changes: 6 additions & 0 deletions types/user-event/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {keyboard} from './keyboard/index'
declare const userEvent: {
keyboard: typeof keyboard
}
export default userEvent
export type {keyboardKey} from './keyboard/index'
15 changes: 15 additions & 0 deletions types/user-event/keyboard/getNextKeyDef.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {keyboardKey, keyboardOptions} from './types'
/**
* Get the next key from keyMap
*
* Keys can be referenced by `{key}` or `{special}` as well as physical locations per `[code]`.
* Everything else will be interpreted as a typed character - e.g. `a`.
* Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`.
*/
export declare function getNextKeyDef(
text: string,
options: keyboardOptions,
): {
keyDef: keyboardKey
consumedLength: number
}
19 changes: 19 additions & 0 deletions types/user-event/keyboard/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {TestInstance} from '../../../types'
import {keyboardOptions, keyboardKey} from './types'
export type {keyboardOptions, keyboardKey}
export declare function keyboard(
instance: TestInstance,
text: string,
options?: Partial<
keyboardOptions & {
delay: number
}
>,
): void | Promise<void>
export declare function keyboardImplementationWrapper(
instance: TestInstance,
text: string,
config?: Partial<keyboardOptions>,
): {
promise: Promise<void>
}
10 changes: 10 additions & 0 deletions types/user-event/keyboard/keyMap.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {keyboardKey} from './types'
/**
* Mapping for a default US-104-QWERTY keyboard
*
* These use ANSI-C quoting, which seems to work for Linux, macOS, and Windows alike
* @see https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#ANSI_002dC-Quoting
* @see https://stackoverflow.com/questions/35429671/detecting-key-press-within-bash-scripts
* @see https://gist.github.com/crutchcorn/2811db78a7b924cf54f4507198427fd2
*/
export declare const defaultKeyMap: keyboardKey[]
7 changes: 7 additions & 0 deletions types/user-event/keyboard/keyboardImplementation.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {TestInstance} from '../../../types'
import {keyboardOptions} from './types'
export declare function keyboardImplementation(
instance: TestInstance,
text: string,
options: keyboardOptions,
): Promise<void>
12 changes: 12 additions & 0 deletions types/user-event/keyboard/types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export type keyboardOptions = {
/** Delay between keystrokes */
delay: number
/** Keyboard layout to use */
keyboardMap: keyboardKey[]
}
export interface keyboardKey {
/** Physical location on a keyboard */
code?: string
/** Character or functional key hex code */
hex?: string
}
1 change: 1 addition & 0 deletions types/user-event/utils.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function wait(time?: number): Promise<void>

0 comments on commit 4e77f64

Please sign in to comment.