@testing-library/react#screen JavaScript 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: index.jsdom.test.jsx    From apps-todo-list with MIT License 6 votes vote down vote up
async function openAsync(table, view, field) {
    act(() => {
        const input = screen.getByLabelText('Table');
        const option = screen.getByText(table);

        userEvent.selectOptions(input, [option]);
    });

    act(() => {
        const input = screen.getByLabelText('View');
        const option = screen.getByText(view);

        userEvent.selectOptions(input, [option]);
    });

    act(() => {
        const input = screen.getByLabelText('Field');
        const option = screen.getByText(field);

        userEvent.selectOptions(input, [option]);
    });

    return waitFor(() => screen.getByRole('button', {name: 'Add'}));
}
Example #2
Source File: RouteDetails.test.js    From viade_en1b with MIT License 6 votes vote down vote up
describe("The component is rendered correctly", () => {
  test("all the information is rendered correctly", () => {
    waitForElement(() => {
      expect(screen.queryByTestId("route-details-description")).not.toBeNull();
      expect(screen.queryByTestId("route-details-button-share")).not.toBeNull();
      expect(
        screen.queryByTestId("route-details-button-delete")
      ).not.toBeNull();
      expect(screen.queryByTestId("route-details-image")).not.toBeNull();
    });
  });
});
Example #3
Source File: Fader.test.js    From expriments_with_react with MIT License 6 votes vote down vote up
test("should render fader component", () => {
  render(<Fader text="test" />);

  const faderElem = screen.getByTestId("fader");

  expect(faderElem).toBeInTheDocument();
  expect(faderElem).toHaveTextContent("test");
  expect(faderElem).toHaveClass("fade-in");
});
Example #4
Source File: LinkOrExternal.test.jsx    From genshin with MIT License 6 votes vote down vote up
describe('LinkOrExternal', () => {
  it('should contain a "a" for external link', () => {
    render(<LinkOrExternal to={HTTPS_EXTERNAL_LINK}>Test link</LinkOrExternal>);
    expect(screen.getByTestId('external-link-node')).toBeTruthy();
  });

  it('should contain a Link component for internal link', () => {
    render(
      <BrowserRouter>
        <LinkOrExternal to={INTERNAL_LINK}>Test link</LinkOrExternal>
      </BrowserRouter>,
    );
    expect(screen.getByTestId('internal-link-node')).toBeTruthy();
  });
});
Example #5
Source File: searchlist.test.js    From healthcare-api-dicom-viewer with Apache License 2.0 6 votes vote down vote up
test('Items do not display until data is done loading', () => {
  const items = generateItems(10);
  const {rerender} = render(
      <SearchList items={items} onClickItem={() => {}} isLoading={true}/>,
  );

  // Ensure no items are displayed
  expect(screen.queryAllByText('item', {exact: false})).toHaveLength(0);

  // Set isLoading=false and check items again
  rerender(
      <SearchList items={items} onClickItem={() => {}} isLoading={false}/>,
  );
  expect(screen.getAllByText('item', {exact: false})).toHaveLength(10);
});
Example #6
Source File: DrinkSearch.test.js    From Simplify-Testing-with-React-Testing-Library with MIT License 6 votes vote down vote up
test('renders mock drink data', async () => {
  render(<DrinkSearch />)
  const searchInput = screen.getByRole('searchbox')

  user.type(searchInput, 'vodka, {enter}')

  expect(
    await screen.findByRole('img', { name: /test drink/i })
  ).toBeInTheDocument()
  expect(
    screen.getByRole('heading', { name: /test drink/i })
  ).toBeInTheDocument()
  expect(screen.getByText(/test ingredient/i)).toBeInTheDocument()
  expect(screen.getByText(/test instructions/i)).toBeInTheDocument()
})
Example #7
Source File: RepositoryHeader.test.js    From edge-frontend with Apache License 2.0 6 votes vote down vote up
describe('RepositoryHeader', () => {
  it('renders correctly', async () => {
    const { container } = render(<RepositoryHeader />);

    expect(screen.getByRole('heading', 'Custom repositories')).toBeDefined();
    expect(
      screen.getByText(
        'Add custom repositories to build RHEL for Edge images with additional packages.'
      )
    ).toBeDefined();
    expect(container.querySelector('div')).toMatchSnapshot();
  });
});
Example #8
Source File: DeleteActivationKeyConfirmationModal.test.js    From sed-frontend with Apache License 2.0 6 votes vote down vote up
describe('Delete Activation Key Confirmation Modal', () => {
  const activationKeyName = 'Test Modal';
  it('renders correctly', () => {
    const props = {
      handleModalToggle: jest.fn(),
      isOpen: true,
      name: activationKeyName,
    };
    render(
      <Provider store={registry.getStore()}>
        <QueryClientProvider client={queryClient}>
          <DeleteActivationKeyConfirmationModal {...props} />
        </QueryClientProvider>
      </Provider>
    );
    expect(screen.getByText(activationKeyName)).toBeInTheDocument();
    expect(screen.getByText('Delete Activation Key?')).toBeInTheDocument();
  });
});
Example #9
Source File: TasksTabs.tests.js    From tasks-frontend with Apache License 2.0 6 votes vote down vote up
describe('TasksTabs', () => {
  let props;

  beforeEach(() => {
    props = {
      className: 'tabs-background',
      tabIndex: 0,
      tabsList: TASKS_PAGE_TABS,
      updateTab: jest.fn(),
    };
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should render correctly', () => {
    const { asFragment } = render(<TasksTabs {...props} />);

    expect(asFragment()).toMatchSnapshot();
  });

  it('should update tab index', async () => {
    render(<TasksTabs {...props} />);

    userEvent.click(screen.getByText('Completed tasks'));
    await waitFor(() =>
      expect(props.updateTab).toHaveBeenCalledWith(expect.anything(), 1)
    );
  });
});
Example #10
Source File: ErrorSummary.test.jsx    From sgmr-service with MIT License 6 votes vote down vote up
test('Renders the ErrorSummary with errors', () => {
  render(<ErrorSummary errors={['Error 1', 'Other error']} />);
  expect(screen.getByTestId('error-summary'))
    .toHaveTextContent(
      'There is a problem'
      + 'Error 1'
      + 'Other error',
    );
});
Example #11
Source File: RadioGroupControl.test.js    From karto with MIT License 6 votes vote down vote up
describe('RadioGroupControl component', () => {

    it('displays provided options', () => {
        const options = ['option1', 'option2'];
        render(
            <RadioGroupControl options={options} value={options[0]} onChange={() => null}/>
        );

        expect(screen.queryByText(options[0])).toBeInTheDocument();
        expect(screen.queryByText(options[1])).toBeInTheDocument();
    });

    it('calls change handler when option is selected', () => {
        const options = ['option1', 'option2'];
        const changeHandler = jest.fn();
        render(
            <RadioGroupControl options={options} value={options[0]} onChange={changeHandler}/>
        );

        fireEvent.click(screen.getByText(options[1]));

        expect(changeHandler).toHaveBeenCalledTimes(1);
        expect(changeHandler).toHaveBeenCalledWith(options[1]);
    });
});
Example #12
Source File: NotFound.test.jsx    From react-enterprise-starter-kit with MIT License 6 votes vote down vote up
describe('[NotFound Component Test Suite]', () => {
  test('should pass if "404" is found in the document', () => {
    render(<NotFound />);
    expect(screen.getByText(ERROR_CODE)).toBeInTheDocument();
  });

  test('should pass if "PAGE NOT FOUND" is found in the document', () => {
    render(<NotFound />);
    expect(screen.getByText(ERROR_TEXT)).toBeInTheDocument();
  });
});
Example #13
Source File: connect_wallet_button.spec.js    From astroport-lbp-frontend with MIT License 6 votes vote down vote up
describe('ConnectWalletButton', () => {
  it('opens extension download URL when extension is not available', async () => {
    connectExtension.mockRejectedValue({ reason: EXTENSION_UNAVAILABLE })

    const windowOpenSpy = jest.spyOn(window, 'open').mockImplementation();

    render(<ConnectWalletButton />);

    await act(async () => {
      await userEvent.click(screen.getByText('Connect Wallet'));
    })

    expect(windowOpenSpy).toHaveBeenCalledWith('https://chrome.google.com/webstore/detail/terra-station/aiifbnbfobpmeekipheeijimdpnlpgpp');
    expect(connectExtension).toHaveBeenCalledTimes(1);

    windowOpenSpy.mockRestore();
  });

  it('displays connecting indicator while connecting' +
    'and then passes wallet/payload to onConnect function when connected', async () => {
    const wallet = jest.fn();

    connectExtension.mockResolvedValue(wallet);

    render(<ConnectWalletButton />);

    await act(async () => {
      await userEvent.click(screen.getByText('Connect Wallet'));
    })

    expect(connectExtension).toHaveBeenCalledTimes(1);
    expect(mockConnectWallet).toHaveBeenCalledTimes(1);
    expect(mockConnectWallet).toHaveBeenCalledWith(wallet);
  });
});
Example #14
Source File: search.test.js    From maps with MIT License 6 votes vote down vote up
test('test if "loading" message appears after submitting a search', async () => {

  render(<Search />)

  screen.getByRole('textbox', { name: 'Name' });
  userEvent.type(screen.getByRole('textbox', { name: 'Name' }), '1335 ASTOR');
  userEvent.click(screen.getByRole('button', {name: /Submit/i}));

  await waitFor(() => screen.findByText(/Loading/i));

  expect(screen.getByText(/Loading.../i)).toHaveTextContent('Loading...');

})
Example #15
Source File: App.test.js    From hk-independent-bus-eta with GNU General Public License v3.0 6 votes vote down vote up
test('renders App', () => {
  render(
    <DbProvider>
      <AppContextProvider>
        <App />
      </AppContextProvider>
    </DbProvider>
  );
  const initializingElement = screen.getByText(/初始設定/);
  expect(initializingElement).toBeInTheDocument();
});
Example #16
Source File: Col.test.js    From react-dsfr with MIT License 6 votes vote down vote up
it('renders Col offset and n properly', () => {
  render(
    <Col n="6" offset="xs-6">Text</Col>,
  );
  const col = screen.getByText('Text');
  expect(col).toBeInTheDocument();
  expect(col.className).toContain('fr-col-offset-xs-6');
  expect(col.className).toContain('fr-col-6');
});
Example #17
Source File: App.test.js    From vacasJunio with MIT License 5 votes vote down vote up
test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});
Example #18
Source File: FriendList.test.js    From viade_en1b with MIT License 5 votes vote down vote up
describe("FriendList component", () => {
  test("renders correctly with normal setting", () => {
    render(
      <IntlProvider key={"en"} locale={"en"} messages={locales["en"]}>
        <FriendList friends={mockFriends}></FriendList>
      </IntlProvider>
    );
    expect(screen.queryByTestId("friend-list-container")).toBeInTheDocument();
    expect(screen.queryByTestId("friend-list-main")).toBeInTheDocument();
    expect(screen.queryByTestId("friend-list-card0")).toBeInTheDocument();
    expect(screen.queryByTestId("friend-list-friend-uri0")).toBeInTheDocument();

    expect(
      screen.queryByTestId("friend-list-friend-name0")
    ).toBeInTheDocument();
    expect(screen.queryByTestId("friend-list-card1")).toBeInTheDocument();
    expect(screen.queryByTestId("friend-list-friend-uri1")).toBeInTheDocument();

    expect(
      screen.queryByTestId("friend-list-friend-name1")
    ).toBeInTheDocument();
  });
  test("renders correctly with checkbox setting", () => {
    render(
      <IntlProvider key={"en"} locale={"en"} messages={locales["en"]}>
        <FriendList
          checked
          onClick={mockOnClick}
          friends={mockFriends}
        ></FriendList>
      </IntlProvider>
    );
    expect(screen.queryByTestId("friend-list-main")).toBeInTheDocument();
    expect(screen.queryByTestId("card0")).toBeInTheDocument();

    expect(mockOnClick).not.toBeCalled();
    fireEvent.click(screen.queryByTestId("card0"));
    expect(mockOnClick).toBeCalled();
    expect(screen.queryByTestId("friend-list-check1")).toBeInTheDocument();
  });
  test("change location", () => {
    const { container } = render(
      <IntlProvider key={"en"} locale={"en"} messages={locales["en"]}>
        <TestingRouter
          redirectUrl={mockFriends[0].uri}
          ComponentWithRedirection={() => <FriendList friends={mockFriends} />}
        />
      </IntlProvider>
    );
    const redirectUrl = mockFriends[0].uri;
    expect(container.innerHTML).toEqual(expect.stringContaining(redirectUrl));
  });
});
Example #19
Source File: Text.test.js    From expriments_with_react with MIT License 5 votes vote down vote up
test("should render text component", () => {
  render(<Text />);

  var textElem = screen.getByTestId("text");

  expect(textElem).toBeInTheDocument();
});
Example #20
Source File: App.test.js    From Classroom-Bot with MIT License 5 votes vote down vote up
test("render topbar", () => {
  render(<TopBar />);
  expect(screen.getByText(/Classroom Slack Bot - Admin/)).toBeInTheDocument();
});
Example #21
Source File: App.test.js    From NFT-Marketplace with MIT License 5 votes vote down vote up
test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});
Example #22
Source File: RenderWithNextLine.test.jsx    From genshin with MIT License 5 votes vote down vote up
describe('RenderWithNextLine', () => {
  it('should render one br tag with a line broke text', () => {
    render(RenderWithNextLine(textWithLineBreak));
    expect(screen.getAllByTestId('line-break')).toHaveLength(2);
  });
});
Example #23
Source File: main.test.js    From healthcare-api-dicom-viewer with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line max-len
test('User can navigate between project, location, dataset, dicomStore, study, and series', async () => {
  render(
      <Main/>,
  );

  // Navigate through: project2 -> location5 -> dataset3 ->
  // dicomStore4 -> study1 -> series1

  // Ensure project1 through project5 are displayed
  await waitFor(() =>
    expect(screen.getAllByText(/^project\d+$/)).toHaveLength(5));
  fireEvent.click(screen.getByText('project2'));

  // Ensure location1 through location5 are displayed
  await waitFor(() =>
    expect(screen.getAllByText(/^location\d+$/)).toHaveLength(5));
  fireEvent.click(screen.getByText('location5'));

  // Ensure dataset1 through dataset5 are displayed
  await waitFor(() =>
    expect(screen.getAllByText(/^dataset\d+$/)).toHaveLength(5));
  fireEvent.click(screen.getByText('dataset3'));

  // Ensure dicomStore1 through dicomStore5 are displayed
  await waitFor(() =>
    expect(screen.getAllByText(/^dicomStore\d+$/)).toHaveLength(5));
  fireEvent.click(screen.getByText('dicomStore4'));

  // Ensure study1 is displayed
  await waitFor(() =>
    expect(screen.getAllByText(/^study\d+$/)).toHaveLength(1));
  fireEvent.click(screen.getByText('study1'));

  // Ensure series1 is displayed
  await waitFor(() =>
    expect(screen.getAllByText(/^series\d+$/)).toHaveLength(1));
  fireEvent.click(screen.getByText('series1'));

  // Confirm that breadcrumbs are all displaying correctly
  expect(screen.queryByText('project2')).not.toBeNull();
  expect(screen.queryByText('location5')).not.toBeNull();
  expect(screen.queryByText('dataset3')).not.toBeNull();
  expect(screen.queryByText('dicomStore4')).not.toBeNull();
  expect(screen.queryByText('study1')).not.toBeNull();
  expect(screen.queryByText('series1')).not.toBeNull();

  // Confirm that clicking a breadcrumb resets state back to
  // search list
  fireEvent.click(screen.getByText('project2'));
  await waitFor(() =>
    expect(screen.queryByText('Select Project')).not.toBeNull());
  await waitFor(() =>
    expect(screen.getAllByText(/^project\d+$/)).toHaveLength(5));
}, 10000);
Example #24
Source File: Login.test.js    From treetracker-admin-client with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('Login Page', () => {
  describe('Layout', () => {
    it('has "Greenstand" logo', () => {
      const { container } = render(<Login />, { wrapper: MemoryRouter });
      const logo = screen.queryByAltText('Greenstand logo');
      expect(logo).toBeInTheDocument();
    });
    it('has "Admin Panel" header', () => {
      const { container } = render(<Login />, { wrapper: MemoryRouter });
      console.log(container.querySelector('div > h2').innerHTML);
      const header = screen.queryByRole('heading', { name: 'Admin Panel' });
      expect(header).toBeInTheDocument();
    });
    it('has username input', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const emailInput = screen.queryByLabelText(/username/i);
      expect(emailInput).toBeInTheDocument();
    });
    it('has password input', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const passwordInput = screen.queryByLabelText(/password/i);
      expect(passwordInput).toBeInTheDocument();
    });
    it('has "Remember me" checkbox', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const checkbox = screen.queryByRole('checkbox', { name: 'Remember me' });
      expect(checkbox).toBeInTheDocument();
    });
    it('has "LOG IN" button', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const loginButton = screen.queryByRole('button', { name: 'LOG IN' });
      expect(loginButton).toBeInTheDocument();
    });
  });
  describe('Interactions', () => {
    it('keeps the "LOG IN" button disabled until one of the input fields is empty', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const emailInput = screen.queryByLabelText(/username/i);
      const passwordInput = screen.queryByLabelText(/password/i);
      const loginButton = screen.queryByRole('button', { name: 'LOG IN' });

      userEvent.type(emailInput, 'admin');
      expect(loginButton).toBeDisabled();
      userEvent.clear(emailInput);

      userEvent.type(passwordInput, 'P4ssword');
      expect(loginButton).toBeDisabled();
      userEvent.clear(passwordInput);

      userEvent.type(emailInput, 'admin');
      userEvent.type(passwordInput, 'P4ssword');
      expect(loginButton).toBeEnabled();
    });
    it('displays spinner after clicking the "LOG IN" button', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const emailInput = screen.queryByLabelText(/username/i);
      const passwordInput = screen.queryByLabelText(/password/i);
      const loginButton = screen.queryByRole('button', { name: 'LOG IN' });

      userEvent.type(emailInput, 'admin');
      userEvent.type(passwordInput, 'P4ssword');
      expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();

      userEvent.click(loginButton);

      const progressbar = screen.queryByRole('progressbar');
      expect(progressbar).toBeInTheDocument();
    });
  });
});
Example #25
Source File: App.test.js    From eth-allowance with MIT License 5 votes vote down vote up
test('renders learn react link', () => {
  render(<header />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});
Example #26
Source File: App.test.js    From treebox with MIT License 5 votes vote down vote up
test("renders learn react link", () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});