diff --git a/src/__tests__/queries.js b/src/__tests__/queries.js index 13e2d7c..9fe08b1 100644 --- a/src/__tests__/queries.js +++ b/src/__tests__/queries.js @@ -21,14 +21,12 @@ test('findByText should throw errors', async () => { }) test('queryByText should find text', async () => { - const props = await render('node', [ + const {queryByText} = await render('node', [ resolve(__dirname, './execute-scripts/list-args.js'), '--version', ]) - const {queryByText} = props; - - expect(await queryByText('--version')).toBeTruthy() + expect(queryByText('--version')).toBeTruthy() }) test('queryByText should not throw errors', async () => { diff --git a/src/__tests__/render-basics.js b/src/__tests__/render-basics.js index a25e8c5..8e10ea5 100644 --- a/src/__tests__/render-basics.js +++ b/src/__tests__/render-basics.js @@ -12,10 +12,9 @@ afterEach(() => { configure(originalConfig) }) -test('Should handle stderr outputs with rejection', async () => { - await expect(() => - render('node', [resolve(__dirname, './execute-scripts/throw.js')]), - ).rejects.toThrow(/Search for this error in stderr/) +test('Should expect error codes when intended', async () => { + const instance = await render('node', [resolve(__dirname, './execute-scripts/throw.js')]) + expect(instance.hasExit()).toMatchObject({exitCode: 1}) }) test('Should handle argument passing', async () => { diff --git a/src/config.ts b/src/config.ts index 8072b05..53ddedf 100644 --- a/src/config.ts +++ b/src/config.ts @@ -13,6 +13,10 @@ interface InternalConfig extends Config { let config: InternalConfig = { testIdAttribute: 'data-testid', asyncUtilTimeout: 1000, + // Short amount of time to wait for your process to spin up after a `spawn`. AFAIK There's unfortunately not much + // of a better way to do this + renderAwaitTime: 100, + // Internal timer time to wait before attempting error recovery debounce action errorDebounceTimeout: 100, // asyncWrapper and advanceTimersWrapper is to support React's async `act` function. // forcing react-testing-library to wrap all async functions would've been @@ -37,7 +41,7 @@ let config: InternalConfig = { const error = new Error( [ message, - testInstance ? `\n${testInstance.stdoutStr}` : '', + testInstance ? `\n${testInstance.stdoutArr.join('\n')}` : '', ] .filter(Boolean) .join('\n\n'), diff --git a/src/pure.ts b/src/pure.ts index d9d8e42..c1ba4b2 100644 --- a/src/pure.ts +++ b/src/pure.ts @@ -4,9 +4,9 @@ import {RenderOptions, RenderResult, TestInstance} from '../types/pure' import {_runObservers} from './mutation-observer' import {getQueriesForElement} from './get-queries-for-instance' import userEvent from './user-event' -import {bindObjectFnsToInstance, debounce, setCurrentInstance} from './helpers' -import {getConfig} from './config' +import {bindObjectFnsToInstance, setCurrentInstance} from './helpers' import {fireEvent} from './events' +import {getConfig} from "./config"; const mountedInstances = new Set() @@ -25,28 +25,23 @@ async function render( }) let _readyPromiseInternals: null | {resolve: Function; reject: Function} = - null - - let _isReadyResolved = false + null const execOutputAPI = { __exitCode: null as null | number, _isOutputAPI: true, _isReady: new Promise( - (resolve, reject) => (_readyPromiseInternals = {resolve, reject}), + (resolve, reject) => (_readyPromiseInternals = {resolve, reject}), ), process: exec, // Clear buffer of stdout to do more accurate `t.regex` checks clear() { - execOutputAPI.stdoutArr = [] + execOutputAPI.stdoutArr = [] }, // An array of strings gathered from stdout when unable to do // `await stdout` because of inquirer interactive prompts stdoutArr: [] as Array, - get stdoutStr(): string { - return this.stdoutArr.join('\n') - }, - set stdoutStr(val: string) {}, + stderrArr: [] as Array, hasExit() { return this.__exitCode === null ? null : {exitCode: this.__exitCode} }, @@ -54,70 +49,41 @@ async function render( mountedInstances.add(execOutputAPI as unknown as TestInstance) - /** - * This method does not throw errors after-the-fact, - * meaning that if post-render errors are thrown, - * they will be missed - * - * THINK: Should we should simply `throw` when this occurs? - * What about cleanup? - * What about interactive errors? - */ - let _errorHasOccured = false - const _errors: Array = [] - exec.stdout.on('data', (result: string | Buffer) => { const resStr = stripFinalNewline(result as string) execOutputAPI.stdoutArr.push(resStr) _runObservers() - if (!_errorHasOccured && _readyPromiseInternals && !_isReadyResolved) { - _readyPromiseInternals.resolve() - _isReadyResolved = true - } - // stdout might contain relevant error info - if (_errorHasOccured && _readyPromiseInternals && !_isReadyResolved) { - _errors.push(result) - } }) - const _onError = () => { - if (!_readyPromiseInternals) return - _readyPromiseInternals.reject(new Error(_errors.join('\n'))) - _isReadyResolved = true - } - - const config = getConfig() - const _throttledOnError = debounce(_onError, config.errorDebounceTimeout) + exec.stderr.on('data', (result: string | Buffer) => { + const resStr = stripFinalNewline(result as string) + execOutputAPI.stderrArr.push(resStr) + _runObservers() + }) - exec.stdout.on('error', result => { - if (_readyPromiseInternals && !_isReadyResolved) { - _errors.push(result) - _throttledOnError() - _errorHasOccured = true + exec.on('error', result => { + if (_readyPromiseInternals) { + _readyPromiseInternals.reject(result); } }) - exec.stderr.on('data', (result: string) => { - if (_readyPromiseInternals && !_isReadyResolved) { - _errors.push(result) - _throttledOnError() - _errorHasOccured = true - } + exec.on('spawn', () => { + setTimeout(() => { + if (_readyPromiseInternals) { + + _readyPromiseInternals.resolve(); + } + }, getConfig().renderAwaitTime) }) exec.on('exit', code => { execOutputAPI.__exitCode = code ?? 0 }) - // TODO: Replace with `debug()` function - if (opts.debug) { - exec.stdout.pipe(process.stdout) - } + setCurrentInstance(execOutputAPI) await execOutputAPI._isReady - setCurrentInstance(execOutputAPI) - return Object.assign( execOutputAPI, { diff --git a/src/queries/text.ts b/src/queries/text.ts index 053a96e..202e7e7 100644 --- a/src/queries/text.ts +++ b/src/queries/text.ts @@ -24,7 +24,7 @@ const queryByTextBase: QueryByText = ( trim, normalizer }) - const str = instance.stdoutStr + const str = instance.stdoutArr.join('\n') if (matcher(str, instance, text, matchNormalizer)) return instance else return null } diff --git a/src/suggestions.js b/src/suggestions.js index d5de0db..30f4e87 100644 --- a/src/suggestions.js +++ b/src/suggestions.js @@ -63,7 +63,7 @@ function canSuggest(currentMethod, requestedMethod, data) { } export function getSuggestedQuery(instance, variant = 'get', method) { - const textContent = normalize(instance.stdoutStr) + const textContent = normalize(instance.stdoutArr.join('\n')) if (canSuggest('Text', method, textContent)) { return makeSuggestion('Text', instance, textContent, {variant}) } diff --git a/types/config.d.ts b/types/config.d.ts index bd8ec9f..44b9b59 100644 --- a/types/config.d.ts +++ b/types/config.d.ts @@ -12,6 +12,7 @@ export interface Config { // eslint-disable-next-line @typescript-eslint/no-explicit-any eventWrapper(cb: (...args: any[]) => any): void asyncUtilTimeout: number + renderAwaitTime: number errorDebounceTimeout: number computedStyleSupportsPseudoElements: boolean defaultHidden: boolean diff --git a/types/pure.d.ts b/types/pure.d.ts index a4f38f8..1a337cb 100644 --- a/types/pure.d.ts +++ b/types/pure.d.ts @@ -7,7 +7,6 @@ export interface TestInstance { clear(): void process: ChildProcessWithoutNullStreams stdoutArr: Array - stdoutStr: string hasExit(): null | {exitCode: number} }