|
| 1 | +import type { ReactTestInstance } from 'react-test-renderer'; |
| 2 | +import { makeQueries } from './makeQueries'; |
| 3 | +import type { |
| 4 | + FindAllByQuery, |
| 5 | + FindByQuery, |
| 6 | + GetAllByQuery, |
| 7 | + GetByQuery, |
| 8 | + QueryAllByQuery, |
| 9 | + QueryByQuery, |
| 10 | +} from './makeQueries'; |
| 11 | + |
| 12 | +type PredicateFn = (instance: ReactTestInstance) => boolean; |
| 13 | +// Not used so far |
| 14 | +type PredicateQueryOptions = void; |
| 15 | + |
| 16 | +const queryAllByPredicate = ( |
| 17 | + instance: ReactTestInstance |
| 18 | +): (( |
| 19 | + predicate: PredicateFn, |
| 20 | + options?: PredicateQueryOptions |
| 21 | +) => Array<ReactTestInstance>) => |
| 22 | + function queryAllByTestIdFn(predicate) { |
| 23 | + const results = instance.findAll( |
| 24 | + (node) => typeof node.type === 'string' && predicate(node) |
| 25 | + ); |
| 26 | + |
| 27 | + return results; |
| 28 | + }; |
| 29 | + |
| 30 | +const getMultipleError = (predicate: PredicateFn) => |
| 31 | + `Found multiple elements matching predicate: ${predicate}`; |
| 32 | + |
| 33 | +const getMissingError = (predicate: PredicateFn) => |
| 34 | + `Unable to find an element matching predicate: ${predicate}`; |
| 35 | + |
| 36 | +const { getBy, getAllBy, queryBy, queryAllBy, findBy, findAllBy } = makeQueries( |
| 37 | + queryAllByPredicate, |
| 38 | + getMissingError, |
| 39 | + getMultipleError |
| 40 | +); |
| 41 | + |
| 42 | +export type ByTestIdQueries = { |
| 43 | + getByPredicate: GetByQuery<PredicateFn, PredicateQueryOptions>; |
| 44 | + getAllByPredicate: GetAllByQuery<PredicateFn, PredicateQueryOptions>; |
| 45 | + queryByPredicate: QueryByQuery<PredicateFn, PredicateQueryOptions>; |
| 46 | + queryAllByPredicate: QueryAllByQuery<PredicateFn, PredicateQueryOptions>; |
| 47 | + findByPredicate: FindByQuery<PredicateFn, PredicateQueryOptions>; |
| 48 | + findAllByPredicate: FindAllByQuery<PredicateFn, PredicateQueryOptions>; |
| 49 | +}; |
| 50 | + |
| 51 | +export const bindByPredicateQueries = ( |
| 52 | + instance: ReactTestInstance |
| 53 | +): ByTestIdQueries => ({ |
| 54 | + getByPredicate: getBy(instance), |
| 55 | + getAllByPredicate: getAllBy(instance), |
| 56 | + queryByPredicate: queryBy(instance), |
| 57 | + queryAllByPredicate: queryAllBy(instance), |
| 58 | + findByPredicate: findBy(instance), |
| 59 | + findAllByPredicate: findAllBy(instance), |
| 60 | +}); |
0 commit comments