@testing-library/react#screen TypeScript Examples

The following examples show how to use @testing-library/react#screen. 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 vote down vote up
/**
 * Change the value in a form field.
 */
export async function changeFieldByRole(role: string, name: RegExp, value: string) {
  const field = screen.getByRole(role, { name: name })
  // eslint-disable-next-line @typescript-eslint/require-await
  await act(async () => {
    fireEvent.change(field, { target: { value: value } })
  })
}
Example #2
Source File: index.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('/index', () => {

    it("renders posts", async () => {
        render(<Page
            posts={{
                pagedMeta: {
                    pageNumber: 1,
                    pageSize: 1,
                    totalElements: 1,
                },
                elements: [{
                    id: '_test_',
                    title: '_test_',
                }]
            }}
        />);

        await screen.findByText('_test_');
    });
})
Example #3
Source File: SQFormDropdown.stories.test.tsx    From SQForm with MIT License 6 votes vote down vote up
it('should show empty value if initial value not in options', () => {
  const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {
    /* do nothing */
  });

  render(
    <SQFormDropdown size="auto" sqFormProps={{initialValues: {state: 'TX'}}} />
  );

  const expandButton = screen.queryByRole('button', {name: /- -/i});

  expect(expandButton).not.toBeInTheDocument();
  expect(consoleWarnSpy).toHaveBeenCalledWith(
    expect.stringMatching(/requested display value.*could not be found/i)
  );

  consoleWarnSpy.mockRestore();
});
Example #4
Source File: FullPageSpinner.test.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
test("renders spinner", async () => {
  render(
    <ChakraProvider>
      <FullPageSpinner />
    </ChakraProvider>
  );

  expect(screen.getByTestId("full-page-spinner")).toBeInTheDocument();
});
Example #5
Source File: TitleBar.test.tsx    From Notepad with MIT License 6 votes vote down vote up
describe("renders home page with contents", () => {
  afterEach(cleanup);

  it("should have 'untitled.txt - notepad' title", () => {
    render(<TitleBar />);
    const titleElement = screen.getByText(/untitled.txt - notepad/i);
    expect(titleElement).toBeInTheDocument();
  });
});
Example #6
Source File: name-edit.spec.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
describe('NameEdit component specs', () => {
  it('should display a label and input elements with empty userName value', () => {
    // Arrange

    // Act
    render(<NameEdit />);

    const h3Element = screen.getByRole('heading', { level: 3 });
    const inputElement = screen.getByRole('textbox', { name: '' });

    // Assert
    expect(h3Element).toBeInTheDocument();
    expect(inputElement).toBeInTheDocument();
  });

  it('should update h3 text when input changes', () => {
    // Arrange

    // Act
    render(<NameEdit />);

    const h3Element = screen.getByRole('heading', { name: '' });
    const inputElement = screen.getByRole('textbox', {
      name: '',
    }) as HTMLInputElement;

    userEvent.type(inputElement, 'John');

    // Assert
    expect(h3Element.textContent).toEqual('John');
    expect(inputElement.value).toEqual('John');
  });
});
Example #7
Source File: initialization.test.tsx    From use-selected-items-hook with MIT License 6 votes vote down vote up
describe("Hook Initialization", () => {
  it("should handle asynchronous items initialization", async () => {
    render(<AsyncInitialization />);

    const paragraphTextRegex = new RegExp(INITIAL_TEST_ITEMS[0].text, "i");
    const paragraph = await screen.findByText(paragraphTextRegex);

    expect(paragraph).toBeInTheDocument();
  });

  it("should initialize items", () => {
    const { result } = renderHook(() => useSelectedItems<TestItem>({
      itemIdentifierKey: "id",
      initialItems: INITIAL_TEST_ITEMS,
    }));

    expect(result.current.items).toHaveLength(INITIAL_TEST_ITEMS.length);
  });

  it("should initialize selected items", () => {
    const initialSelectedItem = INITIAL_TEST_ITEMS[0];

    const { result } = renderHook(() => useSelectedItems<TestItem>({
      itemIdentifierKey: "id",
      initialSelectedItems: [initialSelectedItem],
      initialItems: INITIAL_TEST_ITEMS,
    }));

    expect(result.current.selectedItems).toEqual([initialSelectedItem]);
    expect(result.current.items).toContainEqual(
      expect.objectContaining({
        ...initialSelectedItem,
        isSelected: true,
      }),
    );
  });
});
Example #8
Source File: Snackbar.test.tsx    From atlas with GNU General Public License v3.0 6 votes vote down vote up
describe('Snackar', async () => {
  it('Display snackbar', async () => {
    const { getByText } = render(<TestElement />, {
      wrapper: ({ children }) => (
        <BrowserRouter>
          {children}
          <Snackbars />
        </BrowserRouter>
      ),
    })

    fireEvent.click(screen.getByRole('button'))

    getByText(props.title ?? '')
    getByText(props.description ?? '')
    getByText(props.actionText ?? '')

    await waitForElementToBeRemoved(() => getByText(props.title ?? ''))
  })
})
Example #9
Source File: Header.spec.tsx    From space-traveling with MIT License 6 votes vote down vote up
describe('Header', () => {
  beforeAll(() => {
    mockedPush.mockImplementation(() => Promise.resolve());
    const MockedRouterContext = RouterContext as React.Context<unknown>;
    RouterWrapper = ({ children }): JSX.Element => {
      return (
        <MockedRouterContext.Provider
          value={{
            push: mockedPush,
          }}
        >
          {children}
        </MockedRouterContext.Provider>
      );
    };
  });

  it('should be able to render logo', () => {
    render(<Header />);

    screen.getByAltText('logo');
  });

  it('should be able to navigate to home page after a click', () => {
    render(<Header />, {
      wrapper: RouterWrapper,
    });

    const secondLink = screen.getByAltText('logo');

    fireEvent.click(secondLink);

    expect(mockedPush).toHaveBeenCalledWith(
      '/',
      expect.anything(),
      expect.anything()
    );
  });
});
Example #10
Source File: segmented-button.test.tsx    From keycaplendar with MIT License 6 votes vote down vote up
it("adds selected class to button", () => {
  render(
    <SegmentedButton toggle>
      <SegmentedButtonSegment label="Hi!" selected />
      <SegmentedButtonSegment label="Bye!" />
    </SegmentedButton>
  );
  expect(() =>
    screen.getByText((_, element) =>
      element.classList.contains("segmented-button__segment--selected")
    )
  ).not.toThrow();
});
Example #11
Source File: tab.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Shift tab from first cell of first row', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(
    <>
      <input data-testid="input-before" />
      <DataSheetGrid value={data} columns={columns} ref={ref} lockRows />
      <input data-testid="input-after" />
    </>
  )

  act(() => ref.current.setActiveCell({ col: 0, row: 0 }))

  userEvent.tab({ shift: true })
  expect(ref.current.activeCell).toEqual(null)
  expect(screen.getByTestId('input-before')).toHaveFocus()
})
Example #12
Source File: ProposalCard.test.tsx    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
test('ProposalCard with mocked data', async () => {
  render(<ProposalCard id="test" href="test" />);

  //Title is rendered
  expect(screen.queryByText(proposalTitle)).toBeTruthy();

  // Votes rendered
  expect(screen.queryByText('20%')).toBeTruthy();
  expect(screen.queryByText('40%')).toBeTruthy();

  //fix
  //expect(screen.queryByTestId('proposal-status')).toBeTruthy();

  //Hardcoded data, not yet passed in component from SWR
  expect(screen.queryByText('test.eth')).toBeTruthy();
  // expect(screen.queryByText('150 ETH')).toBeTruthy();
});
Example #13
Source File: Wishlist.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('Wishlist', () => {

  it("renders list", async () => {
    const cstore = getCStore();
    cstore.addToWishlist({
      product: {
        id: 1,
        name: '_test3_'
      }
    });

    render(<AppPropsContext.Provider
      value={{
        pageProps: {
          cmsProps: {
            defaultPages: {
              product: 'product/[slug]',
            }
          }
        },
      }}><Wishlist /></AppPropsContext.Provider>);

    await screen.findByText('_test3_');
  });

})
Example #14
Source File: ExperimentForm.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
test('skipping to submit should check all sections', async () => {
  MockDate.set('2020-08-13')

  const onSubmit = async () => undefined

  const { container } = render(
    <ExperimentForm
      indexedMetrics={Normalizers.indexMetrics(Fixtures.createMetrics(20))}
      indexedSegments={Normalizers.indexSegments(Fixtures.createSegments(20))}
      initialExperiment={experimentToFormData({})}
      onSubmit={onSubmit}
      completionBag={completionBag}
    />,
  )

  const startSectionButton = screen.getByRole('button', { name: /Start/ })
  const basicInfoSectionButton = screen.getByRole('button', { name: /Basic Info/ })
  const audienceSectionButton = screen.getByRole('button', { name: /Audience/ })
  const metricsSectionButton = screen.getByRole('button', { name: /Metrics/ })
  const submitSectionButton = screen.getByRole('button', { name: /Submit/ })

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

  expect(container).toMatchSnapshot()

  expect(isSectionError(startSectionButton)).toBe(true)
  expect(isSectionError(basicInfoSectionButton)).toBe(true)
  expect(isSectionError(audienceSectionButton)).toBe(true)
  expect(isSectionError(metricsSectionButton)).toBe(true)
  expect(isSectionError(submitSectionButton)).toBe(false)

  expect(isSectionComplete(startSectionButton)).toBe(false)
  expect(isSectionComplete(basicInfoSectionButton)).toBe(false)
  expect(isSectionComplete(audienceSectionButton)).toBe(false)
  expect(isSectionComplete(metricsSectionButton)).toBe(false)
  expect(isSectionComplete(submitSectionButton)).toBe(false)
})
Example #15
Source File: SettingsPage.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('admin settings widget', () => {

    it("renders page", async () => {
        render(<SettingsPage
            pluginName="newsletter"
        />);

        await screen.findByText('Export data');
    });
})
Example #16
Source File: ExperimentPageView.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
test('staging experiment shows correct features enabled in overview', async () => {
  await renderExperimentPageView({ experiment: { status: Status.Staging } }, ExperimentView.Overview)

  await waitFor(() => screen.getByRole('button', { name: /Assign Metric/ }))

  expect(getButtonStates()).toEqual({
    editInWizard: true,
    run: true,
    disable: true,
    generalPanelEdit: false,
    assignMetric: false,
    conclusionEdit: null,
  })
})
Example #17
Source File: ProductList.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('ProductList page', () => {

    it("renders products", async () => {
        render(
            <Provider store={store}>
                <Router>
                    <ProductListPage />
                </Router>
            </Provider>
        );

        await screen.findByText('_test1_');
        await screen.findByText('_test2_');
    });
})
Example #18
Source File: MetricFormFields.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
test('renders as expected for conversion metric', async () => {
  const metric = Fixtures.createMetric(1)
  const { container } = render(
    <Formik
      initialValues={{
        metric: metricToFormData(metric),
      }}
      onSubmit={
        /* istanbul ignore next; This is unused */
        () => undefined
      }
    >
      {(formikProps: FormikProps<{ metric: MetricFormData }>) => <MetricFormFields formikProps={formikProps} />}
    </Formik>,
  )

  expect(container).toMatchSnapshot()

  await act(async () => {
    fireEvent.click(screen.getByRole('radio', { name: 'Revenue' }))
  })
})