@testing-library/react#RenderOptions TypeScript Examples
The following examples show how to use
@testing-library/react#RenderOptions.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test-utils.tsx From abacus with GNU General Public License v2.0 | 7 votes |
render: typeof actualRender = <Q extends Queries>(ui: React.ReactElement, options?: RenderOptions<Q>) =>
actualRender(
(
<StaticRouter>
<ThemeProvider>{ui}</ThemeProvider>
</StaticRouter>
) as React.ReactElement,
options,
) as ReturnType<typeof actualRender>
Example #2
Source File: test-utils.tsx From dashboard with Apache License 2.0 | 6 votes |
customRender = (
ui: React.ReactElement,
options?: Omit<RenderOptions, "queries">
) => render(ui, { wrapper: AllTheProviders, ...options })
Example #3
Source File: index.tsx From exevo-pan with The Unlicense | 6 votes |
renderWithProviders = (
ui: ReactElement,
options?: RenderOptions,
): RenderResult => {
const renderResult = render(wrapWithProviders(ui), options)
return {
...renderResult,
rerender: (rerenderedUi): void =>
renderResult.rerender(wrapWithProviders(rerenderedUi)),
}
}
Example #4
Source File: createClientRender.tsx From use-platform with MIT License | 6 votes |
function clientRender<T>(element: ReactElement<T>, options: RenderOptions = {}) {
const { container, hydrate } = options
const render = testingLibraryRender(element, { container, hydrate })
function setProps(props: any) {
render.rerender(cloneElement(element, props))
}
Object.assign(render, { setProps })
return render as Render<T>
}
Example #5
Source File: utils.tsx From safe-apps-sdk with MIT License | 6 votes |
customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'queries'>): RenderResult =>
render(ui, { wrapper: AllTheProviders, ...options })
Example #6
Source File: test-utils.tsx From frontend with MIT License | 6 votes |
customRender = (ui: React.ReactElement, options: RenderOptions = {}) =>
render(ui, { wrapper: Providers, ...options })
Example #7
Source File: testingUtils.tsx From crosshare with GNU Affero General Public License v3.0 | 6 votes |
export function renderWithSnackbar(
ui: ReactElement,
auth: AuthOptions,
options?: RenderOptions
): RenderResult {
return render(ui, {
wrapper: WithAllProviders(auth, true),
...options,
});
}
Example #8
Source File: testingUtils.tsx From crosshare with GNU Affero General Public License v3.0 | 6 votes |
function wrappedRender(
ui: ReactElement,
auth: AuthOptions,
options?: RenderOptions
): RenderResult {
return render(ui, {
wrapper: WithAllProviders(auth),
...options,
});
}
Example #9
Source File: renderWithTheme.tsx From chroma-react with MIT License | 6 votes |
export function renderWithTheme<Q extends Queries>(
ui: React.ReactElement<any>,
options?: RenderOptions<Q> | Omit<RenderOptions, 'queries'>
) {
const { rerender, ...result } = render(
<ThemeProvider theme={theme}>{ui}</ThemeProvider>,
options
);
const wrappedRerender = (ui: React.ReactElement<any>) =>
rerender(<ThemeProvider theme={theme}>{ui}</ThemeProvider>);
return {
...result,
rerender: wrappedRerender,
};
}
Example #10
Source File: tests-utils.tsx From jitsu with MIT License | 6 votes |
renderWithAllProviders = (element: ReactElement, options?: Omit<RenderOptions, "queries">) =>
render(element, { wrapper: AllProviders, ...options })
Example #11
Source File: test.tsx From baleen3 with Apache License 2.0 | 6 votes |
export function renderWithRouter(
ui: Readonly<React.ReactElement>,
route = '/',
options?: Omit<RenderOptions, 'queries'>,
delegate = renderLight
): RenderResult & { history: History } {
const history = createHistory(createMemorySource(route))
return {
...delegate(
<LocationProvider history={history}>{ui}</LocationProvider>,
options
),
history,
}
}
Example #12
Source File: testingLibrary.ts From backstage with Apache License 2.0 | 6 votes |
/**
* @public
* Simplifies rendering of async components in by taking care of the wrapping inside act
*
* @remarks
*
* Components using useEffect to perform an asynchronous action (such as fetch) must be rendered within an async
* act call to properly get the final state, even with mocked responses. This utility method makes the signature a bit
* cleaner, since act doesn't return the result of the evaluated function.
* https://github.com/testing-library/react-testing-library/issues/281
* https://github.com/facebook/react/pull/14853
*/
export async function renderWithEffects(
nodes: ReactElement,
options?: Pick<RenderOptions, 'wrapper'>,
): Promise<RenderResult> {
let value: RenderResult;
await act(async () => {
value = render(nodes, options);
});
return value!;
}
Example #13
Source File: test-utils.tsx From jsonschema-editor-react with Apache License 2.0 | 6 votes |
customRender = (ui: React.ReactElement, options?: RenderOptions) =>
render(ui, { wrapper: AllProviders, ...options })
Example #14
Source File: test.tsx From baleen3 with Apache License 2.0 | 5 votes |
renderDark = (
ui: Readonly<React.ReactElement>,
options?: Omit<RenderOptions, 'queries'>
): RenderResult => render(ui, { wrapper: DarkTheme, ...options })
Example #15
Source File: test.tsx From baleen3 with Apache License 2.0 | 5 votes |
renderLight = (
ui: Readonly<React.ReactElement>,
options?: Omit<RenderOptions, 'queries'>
): RenderResult => render(ui, { wrapper: LightTheme, ...options })
Example #16
Source File: index.tsx From react-starter-boilerplate with MIT License | 5 votes |
function customRender<Q extends Queries>(
ui: React.ReactElement,
options?: RenderOptions<Q> | Omit<RenderOptions, 'queries'>,
): RenderResult<Q> | RenderResult {
return render<Q>(ui, { wrapper: options?.wrapper ?? Wrapper, ...options });
}
Example #17
Source File: testUtil.tsx From UsTaxes with GNU Affero General Public License v3.0 | 5 votes |
renderWithProviders = (
ui: ReactElement,
options: RenderOptions = {}
): RenderResult => render(<Router>{ui}</Router>, options)
Example #18
Source File: testUtils.tsx From crowdsource-dataplatform with MIT License | 5 votes |
customRender = (ui: ReactElement, options?: RenderOptions) =>
render(ui, { wrapper: Wrapper, ...options })
Example #19
Source File: index.test.tsx From erda-ui with GNU Affero General Public License v3.0 | 4 votes |
describe('ContractiveFilter', () => {
const genderMap = [
{
name: 'dop',
id: 'dop',
icon: 'dop',
},
{
name: 'msp',
id: 'msp',
icon: 'msp',
},
{
name: 'cmp',
id: 'cmp',
icon: 'cmp',
},
{
name: 'emp',
id: 'emp',
icon: 'emp',
},
];
const conditionsFilter: ICondition<any>[] = [
{
key: 'name',
type: 'input',
label: 'NAME',
fixed: true,
placeholder: 'filter by name',
customProps: {
className: 'filter-condition-item-name',
},
},
{
key: 'addr',
type: 'input',
label: 'ADDR',
fixed: false,
placeholder: 'filter by addr',
customProps: {
className: 'filter-condition-item-addr',
},
},
{
key: 'platform',
type: 'select',
tips: 'this is tips',
label: 'PLATFORM',
fixed: true,
options: genderMap.map((item) => ({ label: item.name, value: item.id, icon: '' })),
customProps: {
className: 'filter-condition-item-gender',
},
},
{
key: 'createAt',
fixed: true,
type: 'dateRange',
label: 'CREATE_AT',
customProps: {
className: 'filter-condition-item-createAt',
},
},
{
key: 'updateAt',
fixed: true,
type: 'rangePicker',
label: 'UPDATE_AT',
customProps: {
className: 'filter-condition-item-updateAt',
},
},
{
key: 'triggerAt',
fixed: true,
type: 'timespanRange',
label: 'TRIGGER_AT',
customProps: {
className: 'filter-condition-item-triggerAt',
},
},
{
key: 'creator',
fixed: true,
type: 'memberSelector',
label: 'CREATOR',
customProps: {
className: 'filter-condition-item-creator',
},
},
{
key: 'ip',
label: 'creator',
fixed: true,
type: 'custom',
customProps: {
className: 'filter-condition-item-ip',
},
getComp: (props) => {
return (
<input
type="text"
placeholder="filter by ip"
onChange={(e) => {
props.onChange(e.target.value);
}}
/>
);
},
},
{
key: 'scope',
label: 'SCOPE',
fixed: true,
type: 'hidden',
customProps: {
className: 'filter-condition-item-scope',
},
},
];
beforeAll(() => {
jest.mock('lodash');
// @ts-ignore
_.debounce = (fn: Function) => fn;
// @ts-ignore
_.throttle = (fn: Function) => fn;
});
afterAll(() => {
jest.resetAllMocks();
});
const setUp = (props?: Partial<IProps>, option?: Omit<RenderOptions, 'queries'>) => {
const changeFn = jest.fn();
const result = render(
<ContractiveFilter conditions={conditionsFilter} delay={100} {...props} onChange={changeFn} />,
option,
);
const rerender = (n_props: Partial<IProps>) => {
result.rerender(<ContractiveFilter conditions={conditionsFilter} delay={100} {...n_props} onChange={changeFn} />);
};
return {
result,
rerender,
changeFn,
};
};
it('should render well', () => {
const div = document.createElement('div', {});
div.className = 'contractive-filter-date-picker';
const { result, rerender } = setUp(
{
initValue: {
triggerAt: [
{ value: 0, unit: 'ms' },
{ value: 1, unit: 'ms' },
],
},
},
{ container: document.body.appendChild(div) },
);
fireEvent.click(div);
rerender({
values: {
triggerAt: [
{ value: 0, unit: 's' },
{ value: 1, unit: 's' },
],
},
});
expect(result.getByText('Filter')).toBeTruthy();
expect(result.container).isExist('.contractive-filter-item-wrap', 9);
result.unmount();
});
it('should work well with more', async () => {
const { result, changeFn, rerender } = setUp({
conditions: [
...conditionsFilter,
{
key: 'moreSelect',
type: 'select',
label: 'moreSelect',
fixed: false,
},
],
});
fireEvent.click(result.getByText('Filter'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
fireEvent.click(result.getByPlaceholderText('Filter conditions'));
fireEvent.change(result.getByPlaceholderText('Filter conditions'), { target: { value: 'addr' } });
fireEvent.click(result.getByRole('checkbox'));
fireEvent.change(result.getByRole('checkbox'), { target: { checked: true } });
expect(result.container).isExist('.contractive-filter-item-wrap', 10);
fireEvent.change(result.getByPlaceholderText('Filter by addr'), { target: { value: 'erda' } });
expect(changeFn).toHaveBeenLastCalledWith({ addr: 'erda' }, 'addr');
fireEvent.click(result.getByText('Filter'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
fireEvent.click(result.getByText('Clear selected'));
expect(result.container).isExist('.contractive-filter-item-wrap', 9);
expect(changeFn).toHaveBeenLastCalledWith({ addr: undefined }, undefined);
rerender({
values: {
moreSelect: 1,
},
conditions: [
...conditionsFilter,
{
key: 'moreSelect',
type: 'select',
label: 'moreSelect',
fixed: false,
},
],
});
fireEvent.click(result.getByPlaceholderText('Filter conditions'));
fireEvent.change(result.getByPlaceholderText('Filter conditions'), { target: { value: 'moreSelect' } });
fireEvent.click(result.getByRole('checkbox'));
fireEvent.change(result.getByRole('checkbox'), { target: { checked: true } });
expect(result.container).isExist('[name="guanbi-fill"]', 1);
fireEvent.click(result.container.querySelector('[name="guanbi-fill"]')!);
expect(result.container).isExist('[name="guanbi-fill"]', 0);
expect(changeFn).toHaveBeenLastCalledWith({ moreSelect: undefined }, 'moreSelect');
});
it('should getComp work well', () => {
const { result, changeFn } = setUp();
fireEvent.change(result.getByPlaceholderText('filter by ip'), { target: { value: 'erda' } });
expect(changeFn).toHaveBeenLastCalledWith({ ip: 'erda' }, 'ip');
});
it('should work well with input', async () => {
const { result, changeFn } = setUp();
fireEvent.change(result.getByPlaceholderText('Filter by name'), { target: { value: 'erda' } });
expect(changeFn).toHaveBeenLastCalledWith({ name: 'erda' }, 'name');
});
it('should work well with select ', async () => {
const { result, changeFn, rerender } = setUp({
conditions: conditionsFilter.map((item) =>
item.key === 'platform' ? { ...item, haveFilter: true, firstShowLength: 2 } : item,
),
});
fireEvent.click(result.getByText('PLATFORM'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
fireEvent.click(result.getByText(/load more/));
fireEvent.change(result.getByPlaceholderText('Search'), { target: { value: 'dop' } });
fireEvent.click(result.getByText('dop').closest('.option-item')!);
expect(changeFn).toHaveBeenLastCalledWith({ platform: ['dop'] }, 'platform');
fireEvent.click(result.getByText('Clear selected'));
expect(changeFn).toHaveBeenLastCalledWith({ platform: undefined }, 'platform');
rerender({
conditions: conditionsFilter.map((item) =>
item.key === 'platform' ? { ...item, haveFilter: true, required: true } : item,
),
});
expect(result.queryByText('Clear selected')).toBeNull();
});
it('should work well with select single mode', async () => {
const { result, changeFn } = setUp({
conditions: conditionsFilter.map((item) =>
item.key === 'platform'
? { ...item, haveFilter: true, customProps: { ...item.customProps, mode: 'single' } }
: item,
),
});
fireEvent.click(result.getByText('PLATFORM'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
fireEvent.click(result.getByText('dop').closest('.option-item')!);
expect(changeFn).toHaveBeenLastCalledWith({ platform: 'dop' }, 'platform');
expect(result.queryByText('Clear selected')).toBeNull();
});
it('should work well with select quickSelect', async () => {
const quickOperationFn = jest.fn();
const { result } = setUp({
onQuickOperation: quickOperationFn,
conditions: conditionsFilter.map((item) =>
item.key === 'platform'
? {
...item,
haveFilter: true,
quickSelect: {
operationKey: 'quickSelect key',
label: 'quickSelect label',
},
}
: item,
),
});
fireEvent.click(result.getByText('PLATFORM'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
fireEvent.click(result.getByText('quickSelect label'));
expect(quickOperationFn).toHaveBeenCalledTimes(1);
});
it('should work well with select quickAdd', async () => {
const quickOperationFn = jest.fn();
const { result } = setUp({
onQuickOperation: quickOperationFn,
conditions: conditionsFilter.map((item) =>
item.key === 'platform'
? {
...item,
haveFilter: true,
quickAdd: {
operationKey: 'quickAdd key',
show: true,
},
}
: item,
),
});
fireEvent.click(result.getByText('PLATFORM'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
expect(result.getByText('Save')).toHaveClass('not-allowed');
fireEvent.click(result.getByText('Save'));
expect(quickOperationFn).not.toHaveBeenCalled();
fireEvent.change(result.getByPlaceholderText('Please enter'), { target: { value: 'dop' } });
fireEvent.click(result.getByText('Save'));
expect(quickOperationFn).not.toHaveBeenCalled();
fireEvent.change(result.getByPlaceholderText('Please enter'), { target: { value: 'erda' } });
fireEvent.click(result.getByText('Save'));
expect(quickOperationFn).toHaveBeenLastCalledWith({ key: 'quickAdd key', value: 'erda' });
});
it('should work well with select quickDelete', async () => {
const quickOperationFn = jest.fn();
const { result } = setUp({
onQuickOperation: quickOperationFn,
conditions: conditionsFilter.map((item) =>
item.key === 'platform'
? {
...item,
haveFilter: true,
quickDelete: {
operationKey: 'quickDelete key',
show: true,
},
}
: item,
),
});
fireEvent.click(result.getByText('PLATFORM'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
fireEvent.click(result.baseElement.querySelector('.option-item-delete')!);
expect(quickOperationFn).toHaveBeenLastCalledWith({ key: 'quickDelete key', value: 'dop' });
});
it('should work well with select group', async () => {
const quickOperationFn = jest.fn();
const { result, changeFn } = setUp({
onQuickOperation: quickOperationFn,
conditions: conditionsFilter.map((item) =>
item.key === 'platform'
? {
...item,
haveFilter: true,
firstShowLength: 2,
quickDelete: {
operationKey: 'quickDelete key',
show: true,
},
options: genderMap.map((op) => ({
label: op.name,
value: op.id,
children:
op.id === 'dop'
? [
{
label: 'project',
value: 'project',
},
{
label: 'app',
value: 'app',
},
{
label: 'test',
},
]
: [],
})),
}
: item,
),
});
fireEvent.click(result.getByText('PLATFORM'));
await waitFor(() => expect(result.getByRole('menu')).toBeTruthy());
fireEvent.click(result.baseElement.querySelector('[name="shanchu"]')!);
expect(quickOperationFn).toHaveBeenLastCalledWith({ key: 'quickDelete key', value: 'project' });
expect(result.baseElement).not.isExistClass('.option-group-content', 'no-expand');
expect(result.baseElement).isExist('.option-group-content .option-item', 2);
fireEvent.click(result.baseElement.querySelector('.option-group-label')!);
expect(result.baseElement).isExistClass('.option-group-content', 'no-expand');
fireEvent.click(result.baseElement.querySelector('.option-group-content .load-more')!);
expect(result.baseElement).isExist('.option-group-content .option-item', 3);
fireEvent.click(result.getByText('project').closest('.option-item')!);
expect(changeFn).toHaveBeenLastCalledWith({ platform: ['project'] }, 'platform');
});
it('should work well with Duration', async () => {
const spyOnError = jest.spyOn(message, 'error');
const { result, changeFn } = setUp();
const durationInps = result.container.querySelectorAll('.trace-duration .ant-input');
const durationSelect = result.container.querySelectorAll('.trace-duration .ant-select-selector');
fireEvent.mouseDown(durationSelect[1]);
await waitFor(() => expect(result.baseElement).isExist('.ant-select-dropdown', 1));
fireEvent.click(result.getAllByText('s')[1]);
expect(changeFn).toHaveBeenLastCalledWith(
{
triggerAt: [],
},
'triggerAt',
);
fireEvent.change(durationInps[0], { target: { value: 1 } });
fireEvent.change(durationInps[1], { target: { value: 2 } });
expect(changeFn).toHaveBeenLastCalledWith(
{
triggerAt: [
{ timer: 1, unit: 'ms' },
{ timer: 2, unit: 's' },
],
},
'triggerAt',
);
fireEvent.change(durationInps[0], { target: { value: 2000 } });
fireEvent.change(durationInps[1], { target: { value: 1 } });
expect(spyOnError).toHaveBeenLastCalledWith('wrong duration');
spyOnError.mockClear();
});
it.each([{ borderTime: false }, { borderTime: true }])(
'should work well with datePicker with borderTime is $borderTime',
async ({ borderTime }) => {
const { timestamp } = setMockDate();
const { result, changeFn } = setUp({
conditions: conditionsFilter
.filter((item) => item.type !== 'rangePicker')
.map((item) => {
return item.type === 'dateRange'
? {
...item,
customProps: {
...item.customProps,
borderTime,
},
}
: {
...item,
};
}),
});
fireEvent.mouseDown(result.getByPlaceholderText('Start date'));
fireEvent.focus(result.getByPlaceholderText('Start date'));
await waitFor(() => expect(result.baseElement).isExist('.ant-picker-dropdown', 1));
// select start date
fireEvent.click(result.getAllByText('Today')[0]);
fireEvent.mouseDown(result.getByPlaceholderText('End date'));
fireEvent.focus(result.getByPlaceholderText('End date'));
await waitFor(() => expect(result.baseElement).isExist('.ant-picker-dropdown', 2));
// select End date
fireEvent.click(result.getAllByText('Today')[1]);
const createAt = borderTime ? [timestamp.startOfDay, timestamp.endOfDay] : [timestamp.current, timestamp.current];
expect(changeFn).toHaveBeenLastCalledWith({ createAt }, 'createAt');
resetMockDate();
},
);
it.each([{ borderTime: false }, { borderTime: true }])(
'should work well with rangePicker with borderTime is $borderTime',
async ({ borderTime }) => {
const { moment, timestamp } = setMockDate();
const currentDay = moment.format('YYYY-MM-DD');
const nextDay = moment.clone().add(1, 'day');
const nextDayStr = nextDay.format('YYYY-MM-DD');
const { result, changeFn } = setUp({
conditions: conditionsFilter
.filter((item) => item.type !== 'dateRange')
.map((item) => {
return item.type === 'rangePicker'
? {
...item,
customProps: {
...item.customProps,
borderTime,
ranges: [
{
'last 1 month': { label: 'last 1 month', range: [moment.clone().subtract(30, 'days'), moment] },
},
],
selectableTime: [moment.clone().subtract(10, 'days'), moment.clone().add(10, 'days')],
},
}
: {
...item,
};
}),
});
fireEvent.mouseDown(result.getByPlaceholderText('Start date'));
fireEvent.focus(result.getByPlaceholderText('Start date'));
await waitFor(() => expect(result.baseElement).isExist('.ant-picker-range-wrapper', 1));
fireEvent.click(result.baseElement.querySelector(`[title="${currentDay}"]`)!);
fireEvent.click(result.baseElement.querySelector(`[title="${nextDayStr}"]`)!);
const updateAt = borderTime
? [timestamp.startOfDay, nextDay.clone().endOf('day').valueOf()]
: [timestamp.current, nextDay.clone().valueOf()];
expect(changeFn).toHaveBeenLastCalledWith({ updateAt }, 'updateAt');
resetMockDate();
},
);
it('should work well with memberSelector', async () => {
const { result, changeFn } = setUp();
fireEvent.click(result.container.querySelector('.member-value')!);
fireEvent.click(result.getByText('triggerChange'));
expect(changeFn).toHaveBeenLastCalledWith({ creator: 'erda' }, 'creator');
});
it('should getSelectOptions work well', () => {
const options = [
{
label: 'dop',
value: 'dop',
children: [
{
label: 'project',
value: 'project',
},
{
label: 'application',
value: 'application',
},
],
},
{
label: 'msp',
value: 'msp',
children: [
{
label: 'alarm',
value: 'alarm',
},
],
},
{
label: 'cmp',
value: 'cmp',
},
];
expect(getSelectOptions(options, '')).toStrictEqual(options);
expect(getSelectOptions(options, 'application')).toStrictEqual([
{ label: 'dop', value: 'dop', children: [{ label: 'application', value: 'application' }] },
]);
});
});