Skip to content

Commit

Permalink
Use selectors from npm
Browse files Browse the repository at this point in the history
  • Loading branch information
asimonok committed Jul 17, 2023
1 parent bc28374 commit 5af6345
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 51 deletions.
2 changes: 1 addition & 1 deletion src/components/Collapse/Collapse.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { getJestSelectors } from '../../utils';
import { getJestSelectors } from '@volkovlabs/jest-selectors';
import { Collapse } from './Collapse';

type Props = React.ComponentProps<typeof Collapse>;
Expand Down
51 changes: 1 addition & 50 deletions src/utils/tests.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,6 @@
import { BoundFunctions, GetByBoundAttribute, Queries, Screen } from '@testing-library/react';
import { getJestSelectors } from '@volkovlabs/jest-selectors';
import { TestIds } from '../constants';

/**
* Jest Selector
*/
type JestSelector<Args extends unknown[]> = (
noThrowOnNotFound?: boolean,
...args: Args
) => ReturnType<GetByBoundAttribute>;

/**
* Jest Selectors
*/
type JestSelectors<T> = {
[K in keyof T]: T[K] extends (...args: infer Args) => void ? JestSelector<Args> : JestSelector<[]>;
};

/**
* Get Jest Selectors
* @param selectors
* @param enforceTestIdSelectorForKeys
*/
export const getJestSelectors =
<Selectors extends Record<keyof Selectors, Selectors[keyof Selectors]>>(
selectors: Selectors,
enforceTestIdSelectorForKeys: Array<keyof Selectors> = []
): ((screen: Screen | BoundFunctions<Queries>) => JestSelectors<Selectors>) =>
(screen) => {
return Object.entries(selectors).reduce((acc, [key, selector]) => {
/**
* Get Element function
* @param noThrowOnNotFound
* @param args
*/
const getElement = (noThrowOnNotFound = false, ...args: unknown[]) => {
const value = typeof selector === 'function' ? selector(...args) : selector;

if (value.startsWith('data-testid') || enforceTestIdSelectorForKeys.includes(key as keyof Selectors)) {
return noThrowOnNotFound ? screen.queryByTestId(value) : screen.getByTestId(value);
}

return noThrowOnNotFound ? screen.queryByLabelText(value) : screen.getByLabelText(value);
};

return {
...acc,
[key]: getElement,
};
}, {} as JestSelectors<Selectors>);
};

/**
* Get Custom Code Editor Selectors
*/
Expand Down

0 comments on commit 5af6345

Please sign in to comment.