@testing-library/react#RenderResult TypeScript Examples

The following examples show how to use @testing-library/react#RenderResult. 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: ClickableText.spec.tsx    From apps with GNU Affero General Public License v3.0 7 votes vote down vote up
renderComponent = <
  C extends HTMLElement = HTMLButtonElement,
  P = HTMLAttributes<C>,
>({
  children,
  ...props
}: Partial<
  BaseClickableTextProps & P & { children: ReactNode }
>): RenderResult => {
  return render(<ClickableText {...props}>{children}</ClickableText>);
}
Example #2
Source File: test_utils.ts    From firebase-tools-ui with Apache License 2.0 7 votes vote down vote up
/*
 * Render a component containing a MDC dialog, and wait for the dialog to be
 * fully open. Silences act(...) warnings from RMWC <Dialog>s.
 *
 * This is syntatic sugar for render() and then waitForDialogsToOpen().
 */
export async function renderDialogWithFirestore(
  ui: (firestore: firebase.firestore.Firestore) => Promise<React.ReactElement>
): Promise<RenderResult> {
  const result = await renderWithFirestore(ui);
  await waitForDialogsToOpen(result.container);
  return result;
}
Example #3
Source File: test-utils.tsx    From fhir-validator-app with Apache License 2.0 7 votes vote down vote up
renderWithRouter = (
  ui: JSX.Element,
  { route = '/', history = createMemoryHistory({ initialEntries: [route] }) }: RenderOptions = {}
): RenderResult & { history: MemoryHistory } => {
  const Wrapper: FC = ({ children }) => <Router history={history}>{children}</Router>;
  return {
    ...render(ui, { wrapper: Wrapper }),
    history,
  };
}
Example #4
Source File: filterTitle.test.tsx    From one-platform with MIT License 6 votes vote down vote up
describe('Filter Title', () => {
  let component: RenderResult;
  beforeEach(() => {
    component = render(<FilterTitle title="Applications" onClear={mockFn} isClearable />);
  });

  afterEach(() => {
    component.unmount();
  });

  test('Should have a title', () => {
    const textEl = screen.getByText(/Applications/i);
    expect(textEl).toBeInTheDocument();
  });

  test('Should fire onClear event on clear button click', () => {
    const btn = screen.getByText(/clear/i);
    fireEvent.click(btn);
    expect(mockFn.mock.calls.length).toBe(1);
  });
});
Example #5
Source File: DonateButton.test.tsx    From panvala with Apache License 2.0 6 votes vote down vote up
describe('DonateButton', () => {
  let container: RenderResult;

  beforeEach(() => {
    // Render
    container = render(
      <ThemeProvider theme={theme}>
        <DonateButton disabled={false} text="Donate now" handleClick={clickHandler} />
      </ThemeProvider>
    );
  });

  test('should render the component', () => {
    // Get the element
    const instance = container.getByText('Donate now');

    // Snapshot
    expect(instance).toMatchSnapshot();
  });

  test('should have been called twice if clicked', () => {
    // Get the element
    const instance = container.getByText('Donate now');

    // Mock: click button
    instance.click();
    instance.click();
    expect(clickHandler).toHaveBeenCalledTimes(2);
  });
});
Example #6
Source File: TableForm.test.tsx    From ant-extensions with MIT License 6 votes vote down vote up
describe("PageMaker", () => {
  let fragment: RenderResult;

  beforeEach(() => {
    fragment = render(<div />, {
      wrapper: TestWrapper
    });
  });

  afterAll(() => {
    fragment.unmount();
  });

  it("should render", (done) => {
    expect(fragment.container).toMatchSnapshot();
    done();
  });

  it.todo("should fire change event");
});
Example #7
Source File: testUtils.tsx    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
export function renderWithStyledTheme(
  component: React.ReactNode,
  renderFunction: any = render,
  options?: any
): RenderResult {
  return {
    ...renderFunction(
      <ThemeProvider theme={theme}>{component}</ThemeProvider>,
      options
    ),
  };
}
Example #8
Source File: FlatRoutes.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
function makeRouteRenderer(node: ReactNode) {
  let rendered: RenderResult | undefined = undefined;
  return (path: string) => {
    const content = (
      <Wrapper>
        <AppContextProvider
          appContext={
            {
              getComponents: () => ({
                NotFoundErrorPage: () => <>Not Found</>,
              }),
            } as unknown as AppContext
          }
        >
          <MemoryRouter initialEntries={[path]} children={node} />
        </AppContextProvider>
      </Wrapper>
    );
    if (rendered) {
      rendered.unmount();
      rendered.rerender(content);
    } else {
      rendered = render(content);
    }
    return rendered;
  };
}
Example #9
Source File: CheckBoxGroup.test.tsx    From ke with MIT License 6 votes vote down vote up
getComponent = (value: Model[], defaultValue: string[]): RenderResult =>
  render(
    <CheckBoxGroup
      value={value}
      getKey={getValue}
      getValue={getValue}
      getLabel={getLabel}
      onChange={onChangeMock}
      defaultValue={defaultValue}
    />
  )
Example #10
Source File: ens.test.tsx    From safe-airdrop with MIT License 6 votes vote down vote up
test("isEnsEnabled with ens capable network", async () => {
  const fakeWeb3Provider: any = {
    getNetwork: () => {
      return Promise.resolve({ chainId: 4, network: "rinkeby", ensAddress: "0x00000000000001" });
    },
  };

  jest.spyOn(ethers.providers, "Web3Provider").mockImplementation(() => fakeWeb3Provider);
  let renderedContainer: undefined | RenderResult;
  act(() => {
    if (container !== null) {
      renderedContainer = renderTestComponent(container);
    }
  });

  sendSafeInfo();

  expect(renderedContainer).toBeTruthy();
  const ensEnabledElement = await screen.findByTestId("isEnsEnabled");
  expect(ensEnabledElement?.innerHTML).toBe("true");
});
Example #11
Source File: MainList.spec.tsx    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
describe('Navigation Main List', () => {

  function renderComponent(): RenderResult {
    return render(
      <MemoryRouter>
        <Nav
          onSelect={() => jest.fn()}
          theme="light"
        >
          <NavigationMainList activePath="" />
        </Nav>
      </MemoryRouter>
    );
  }

  it('should have correct number of main navigation items', () => {
    renderComponent();

    const navLinks = screen.getAllByRole('link');
    expect(navLinks.length).toEqual(2);
  });

  it('should have correct navigation item labels', () => {
    renderComponent();

    const navLinks = screen.getAllByRole('link');

    expect(navLinks[0]).toHaveTextContent('Get Started Page');
    expect(navLinks[1]).toHaveTextContent('Workspaces');
  });

});
Example #12
Source File: Settings.spec.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
renderComponent = (
  user: LoggedUser = defaultUser,
  settings: RemoteSettings = defaultSettings,
): RenderResult => {
  const queryClient = new QueryClient();
  return render(
    <QueryClientProvider client={queryClient}>
      <AuthContext.Provider
        value={{
          user,
          shouldShowLogin: false,
          showLogin,
          logout: jest.fn(),
          updateUser: jest.fn(),
          tokenRefreshed: true,
          getRedirectUri: jest.fn(),
          loadedUserFromCache: true,
          loginState: null,
          loadingUser: false,
          closeLogin: jest.fn(),
          trackingId: user?.id,
        }}
      >
        <SettingsContextProvider
          settings={settings}
          updateSettings={updateSettings}
          loadedSettings
        >
          <Settings />
        </SettingsContextProvider>
      </AuthContext.Provider>
    </QueryClientProvider>,
  );
}
Example #13
Source File: test.tsx    From baleen3 with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: index.test.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('Ellipsis', () => {
  const setDomBounding = (data: Partial<HTMLElement>) => {
    Object.keys(data ?? {}).forEach((prop) => {
      Object.defineProperty(HTMLElement.prototype, prop, {
        configurable: true,
        writable: true,
        // @ts-ignore no fix
        value: data[prop],
      });
    });
  };
  const title = 'this is a very long text';
  const triggerEvent = (result: RenderResult) => {
    act(() => {
      fireEvent.mouseEnter(result.getByText(title));
      jest.runAllTimers();
      userEvent.hover(result.container.querySelector('.erda-ellipsis')!);
    });
  };
  it('should work well', async () => {
    jest.useFakeTimers();
    const result = render(<Ellipsis title={title} />);
    triggerEvent(result);
    await waitFor(() => expect(result.queryByRole('tooltip')).not.toBeInTheDocument());
    setDomBounding({ offsetWidth: 200, scrollWidth: 199, clientWidth: 200 });
    triggerEvent(result);
    await waitFor(() => expect(result.queryByRole('tooltip')).not.toBeInTheDocument());
    setDomBounding({ offsetWidth: 100, scrollWidth: 200, clientWidth: 100 });
    triggerEvent(result);
    await waitFor(() => expect(result.queryByRole('tooltip')).toBeInTheDocument());
    expect(result.getAllByText(title)).toHaveLength(2);
    jest.useRealTimers();
  });
});
Example #15
Source File: test-utils.ts    From excalidraw with MIT License 6 votes vote down vote up
/**
   * automatically updated on each call to render()
   */
  static renderResult: RenderResult<typeof customQueries> = null!;
Example #16
Source File: Resource.test.tsx    From fhir-validator-app with Apache License 2.0 6 votes vote down vote up
function renderResource(props: Partial<ResourceProps> = {}): RenderResult {
  const defaultProps: ResourceProps = {
    resource: '{ "foo": "bar"}',
    contentType: 'json',
    errors: [],
    warnings: [],
    information: [],
  };
  return render(<Resource {...defaultProps} {...props} />);
}
Example #17
Source File: DayPicker.test.tsx    From chroma-react with MIT License 6 votes vote down vote up
BLUR_SCENARIOS: {
  name: string;
  from: (view: RenderResult) => HTMLElement;
  to: (view: RenderResult) => HTMLElement;
  shouldClose: boolean;
}[] = [
  {
    name: 'input -> calendar',
    from: (view) => view.getByRole('textbox'),
    to: (view) => view.getByLabelText('Fri Nov 12 2021'),
    shouldClose: false,
  },
  {
    name: 'calendar -> input',
    from: (view) => view.getByLabelText('Fri Nov 12 2021'),
    to: (view) => view.getByRole('textbox'),
    shouldClose: false,
  },
  {
    name: 'calendar -> calendar',
    from: (view) => view.getByLabelText('Fri Nov 12 2021'),
    to: (view) => view.getByLabelText('Sat Nov 13 2021'),
    shouldClose: false,
  },
  {
    name: 'input -> outside',
    from: (view) => view.getByRole('textbox'),
    to: (view) => view.getByText(OUTSIDE_TEXT),
    shouldClose: true,
  },
  {
    name: 'calendar -> outside',
    from: (view) => view.getByLabelText('Fri Nov 12 2021'),
    to: (view) => view.getByText(OUTSIDE_TEXT),
    shouldClose: true,
  },
]
Example #18
Source File: Base.test.tsx    From mail-my-ballot with Apache License 2.0 6 votes vote down vote up
fillWithoutSigning = ({getByLabelText, getByTestId}: RenderResult) => {
  act(() => {
    fireEvent.change(getByLabelText(/^Full Name/i), {
      target: {
        value: 'Bob Smith'
      },
    })
    fireEvent.change(getByLabelText(/^Birthdate/i), {
      target: {
        value: '03/22/1900'
      },
    })
    fireEvent.change(getByLabelText(/^Email/i), {
      target: {
        value: '[email protected]'
      },
    })
    fireEvent.change(getByLabelText(/^Phone/i), {
      target: {
        value: '123-456-7890'
      },
    })

    SignatureCanvas.prototype.isEmpty = jest.fn(() => true)
    mocked(window, true).alert = jest.fn()

    fireEvent.click(getByTestId('submit'), {
      bubbles: true,
      cancelable: true,
    })
  })
}
Example #19
Source File: testingUtils.tsx    From crosshare with GNU Affero General Public License v3.0 6 votes vote down vote up
function wrappedRender(
  ui: ReactElement,
  auth: AuthOptions,
  options?: RenderOptions
): RenderResult {
  return render(ui, {
    wrapper: WithAllProviders(auth),
    ...options,
  });
}
Example #20
Source File: testUtils.tsx    From antibody-web with MIT License 6 votes vote down vote up
renderWithStubTestContext = (component: JSX.Element, api = {}, recordProperties: Partial<TestRecord>): [RenderResult, AppContextType, TestContextType] => {

  const testContext: TestContextType = {
    state: {
      testRecord: { ...defaultRecord, ...recordProperties }
    },
    dispatch: () => { }
  };

  const [result, appContext] = renderWithStubAppContext(
    <TestContext.Provider value={testContext}>
      {component}
    </TestContext.Provider>,
    api
  );

  return [result, appContext, testContext];
}
Example #21
Source File: Toolbar.test.tsx    From pybricks-code with MIT License 6 votes vote down vote up
function getButtons(toolbar: RenderResult): {
    button1: HTMLElement;
    button2: HTMLElement;
    button3: HTMLElement;
} {
    const button1 = toolbar.getByRole('button', { name: 'Button 1' });
    const button2 = toolbar.getByRole('button', { name: 'Button 2' });
    const button3 = toolbar.getByRole('button', { name: 'Button 3' });

    return { button1, button2, button3 };
}
Example #22
Source File: utils.tsx    From safe-apps-sdk with MIT License 6 votes vote down vote up
customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'queries'>): RenderResult =>
  render(ui, { wrapper: AllTheProviders, ...options })
Example #23
Source File: index.tsx    From exevo-pan with The Unlicense 6 votes vote down vote up
renderWithProviders = (
  ui: ReactElement,
  options?: RenderOptions,
): RenderResult => {
  const renderResult = render(wrapWithProviders(ui), options)

  return {
    ...renderResult,
    rerender: (rerenderedUi): void =>
      renderResult.rerender(wrapWithProviders(rerenderedUi)),
  }
}
Example #24
Source File: feedbackCard.test.tsx    From one-platform with MIT License 5 votes vote down vote up
describe('Feedback Card', () => {
  let component: RenderResult;
  const feedback = mockFeedbacks[0];
  beforeEach(() => {
    component = render(
      <FeedbackCard
        title={feedback.createdBy.cn}
        createdOn={feedback.createdOn}
        description={feedback.summary}
        experience={feedback.experience}
        module={feedback.module}
        category={feedback.category}
        state={feedback.state}
        onClick={mockFn}
      />
    );
  });

  afterEach(() => {
    component.unmount();
  });

  test('Check title is present', () => {
    const textEl = screen.getByText(/lore - 27 January, 2022/i);
    expect(textEl).toBeInTheDocument();
  });

  test('Check popup opens on click', () => {
    const btn = screen.getByText(/view more/i);
    fireEvent.click(btn);
    expect(mockFn.mock.calls.length).toBe(1);
  });

  test('When summary is short ellipsis should  be hidden', () => {
    const textEl = screen.queryByText(/\.\.\./i);
    expect(textEl).toBeNull();
  });

  test('When summary is longer than 200 ellipsis', () => {
    const desc = new Array(300).fill('a').join();
    component.unmount();
    component = render(
      <FeedbackCard
        title={feedback.createdBy.cn}
        createdOn={feedback.createdOn}
        description={desc}
        experience={feedback.experience}
        module={feedback.module}
        category={feedback.category}
        state={feedback.state}
        onClick={mockFn}
      />
    );
    const textEl = screen.getByText(/\.\.\./i);
    expect(textEl).toBeInTheDocument();
  });
});
Example #25
Source File: test-helpers.ts    From react-final-table with MIT License 5 votes vote down vote up
export function getBodyRows<T extends RenderResult>(table: T) {
  return table.container.querySelectorAll('tbody > tr');
}
Example #26
Source File: index.test.tsx    From ii-admin-base with MIT License 5 votes vote down vote up
wrapper: RenderResult
Example #27
Source File: index.tsx    From react-starter-boilerplate with MIT License 5 votes vote down vote up
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 #28
Source File: RelativeDatePicker.test.tsx    From ant-extensions with MIT License 5 votes vote down vote up
describe("RelativeDatePicker", () => {
  let fragment: RenderResult;
  const initialValue = "$now";

  beforeEach(() => {
    fragment = render(<RelativeDatePicker value={initialValue} />, {
      wrapper: TestWrapper
    });
  });

  afterAll(() => {
    fragment.unmount();
  });

  it("should render", (done) => {
    expect(fragment.container).toMatchSnapshot();
    expect(fragment.queryByDisplayValue(DateUtils.label(initialValue))).not.toBeNull();
    done();
  });

  it("should set quick value", (done) => {
    const newValue = "$week";
    fragment.rerender(<RelativeDatePicker value={newValue} />);
    expect(fragment.container).toMatchSnapshot();
    expect(fragment.queryByDisplayValue(DateUtils.label(newValue))).not.toBeNull();

    const inputEl = fragment.getByTestId("input-el");
    fireEvent.click(inputEl);
    expect(fragment.baseElement.querySelector(".ant-tabs")).not.toBeNull();
    // expect(fragment.getByTestId("tab-quick")).toHaveClass("ant-tabs-tabpane-active");

    done();
  });

  it("should set absolute value", (done) => {
    const newValue = "2020-01-01T00:00:00.000Z";
    fragment.rerender(<RelativeDatePicker value={newValue} />);
    expect(fragment.container).toMatchSnapshot();
    expect(fragment.queryByDisplayValue(DateUtils.label(newValue))).not.toBeNull();

    const inputEl = fragment.getByTestId("input-el");
    fireEvent.click(inputEl);
    expect(fragment.baseElement.querySelector(".ant-tabs")).not.toBeNull();
    // expect(fragment.getByTestId("tab-absolute")).toHaveClass("ant-tabs-tabpane-active");

    done();
  });

  it.todo("should fire change event");
});
Example #29
Source File: SupportButton.test.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
describe('<SupportButton />', () => {
  it('renders without exploding', async () => {
    let renderResult: RenderResult;

    await act(async () => {
      renderResult = render(wrapInTestApp(<SupportButton />));
    });

    await waitFor(() =>
      expect(renderResult.getByTestId(SUPPORT_BUTTON_ID)).toBeInTheDocument(),
    );
  });

  it('supports passing a title', async () => {
    await renderInTestApp(<SupportButton title="Custom title" />);
    fireEvent.click(screen.getByTestId(SUPPORT_BUTTON_ID));
    expect(screen.getByText('Custom title')).toBeInTheDocument();
  });

  it('shows popover on click', async () => {
    let renderResult: RenderResult;

    await act(async () => {
      renderResult = render(wrapInTestApp(<SupportButton />));
    });

    let button: HTMLElement;

    await waitFor(() => {
      expect(renderResult.getByTestId(SUPPORT_BUTTON_ID)).toBeInTheDocument();
      button = renderResult.getByTestId(SUPPORT_BUTTON_ID);
    });

    await act(async () => {
      fireEvent.click(button);
    });

    await waitFor(() => {
      expect(renderResult.getByTestId(POPOVER_ID)).toBeInTheDocument();
    });
  });
});