🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

Overview

React Testing Library

goat

Simple and complete React DOM testing utilities that encourage good testing practices.


Read The Docs | Edit the docs



Build Status Code Coverage version downloads MIT License All Contributors PRs Welcome Code of Conduct Discord

Watch on GitHub Star on GitHub Tweet

Table of Contents

The problem

You want to write maintainable tests for your React components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

The solution

The React Testing Library is a very lightweight solution for testing React components. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices. Its primary guiding principle is:

The more your tests resemble the way your software is used, the more confidence they can give you.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install --save-dev @testing-library/react

or

for installation via yarn

yarn add --dev @testing-library/react

This library has peerDependencies listings for react and react-dom.

You may also be interested in installing @testing-library/jest-dom so you can use the custom jest matchers.

Docs

Suppressing unnecessary warnings on React DOM 16.8

There is a known compatibility issue with React DOM 16.8 where you will see the following warning:

Warning: An update to ComponentName inside a test was not wrapped in act(...).

If you cannot upgrade to React DOM 16.9, you may suppress the warnings by adding the following snippet to your test configuration (learn more):

// this is just a little hack to silence a warning that we'll get until we
// upgrade to 16.9. See also: https://github.com/facebook/react/pull/14853
const originalError = console.error
beforeAll(() => {
  console.error = (...args) => {
    if (/Warning.*not wrapped in act/.test(args[0])) {
      return
    }
    originalError.call(console, ...args)
  }
})

afterAll(() => {
  console.error = originalError
})

Examples

Basic Example

// hidden-message.js
import * as React from 'react'

// NOTE: React Testing Library works well with React Hooks and classes.
// Your tests will be the same regardless of how you write your components.
function HiddenMessage({children}) {
  const [showMessage, setShowMessage] = React.useState(false)
  return (
    <div>
      <label htmlFor="toggle">Show Message</label>
      <input
        id="toggle"
        type="checkbox"
        onChange={e => setShowMessage(e.target.checked)}
        checked={showMessage}
      />
      {showMessage ? children : null}
    </div>
  )
}

export default HiddenMessage
// __tests__/hidden-message.js
// these imports are something you'd normally configure Jest to import for you
// automatically. Learn more in the setup docs: https://testing-library.com/docs/react-testing-library/setup#cleanup
import '@testing-library/jest-dom'
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required

import * as React from 'react'
import {render, fireEvent, screen} from '@testing-library/react'
import HiddenMessage from '../hidden-message'

test('shows the children when the checkbox is checked', () => {
  const testMessage = 'Test Message'
  render(<HiddenMessage>{testMessage}</HiddenMessage>)

  // query* functions will return the element or null if it cannot be found
  // get* functions will return the element or throw an error if it cannot be found
  expect(screen.queryByText(testMessage)).toBeNull()

  // the queries can accept a regex to make your selectors more resilient to content tweaks and changes.
  fireEvent.click(screen.getByLabelText(/show/i))

  // .toBeInTheDocument() is an assertion that comes from jest-dom
  // otherwise you could use .toBeDefined()
  expect(screen.getByText(testMessage)).toBeInTheDocument()
})

Complex Example

// login.js
import * as React from 'react'

function Login() {
  const [state, setState] = React.useReducer((s, a) => ({...s, ...a}), {
    resolved: false,
    loading: false,
    error: null,
  })

  function handleSubmit(event) {
    event.preventDefault()
    const {usernameInput, passwordInput} = event.target.elements

    setState({loading: true, resolved: false, error: null})

    window
      .fetch('/api/login', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          username: usernameInput.value,
          password: passwordInput.value,
        }),
      })
      .then(r => r.json().then(data => (r.ok ? data : Promise.reject(data))))
      .then(
        user => {
          setState({loading: false, resolved: true, error: null})
          window.localStorage.setItem('token', user.token)
        },
        error => {
          setState({loading: false, resolved: false, error: error.message})
        },
      )
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="usernameInput">Username</label>
          <input id="usernameInput" />
        </div>
        <div>
          <label htmlFor="passwordInput">Password</label>
          <input id="passwordInput" type="password" />
        </div>
        <button type="submit">Submit{state.loading ? '...' : null}</button>
      </form>
      {state.error ? <div role="alert">{state.error}</div> : null}
      {state.resolved ? (
        <div role="alert">Congrats! You're signed in!</div>
      ) : null}
    </div>
  )
}

export default Login
// __tests__/login.js
// again, these first two imports are something you'd normally handle in
// your testing framework configuration rather than importing them in every file.
import '@testing-library/jest-dom'
import * as React from 'react'
// import API mocking utilities from Mock Service Worker.
import {rest} from 'msw'
import {setupServer} from 'msw/node'
// import testing utilities
import {render, fireEvent, screen} from '@testing-library/react'
import Login from '../login'

const fakeUserResponse = {token: 'fake_user_token'}
const server = setupServer(
  rest.post('/api/login', (req, res, ctx) => {
    return res(ctx.json(fakeUserResponse))
  }),
)

beforeAll(() => server.listen())
afterEach(() => {
  server.resetHandlers()
  window.localStorage.removeItem('token')
})
afterAll(() => server.close())

test('allows the user to login successfully', async () => {
  render(<Login />)

  // fill out the form
  fireEvent.change(screen.getByLabelText(/username/i), {
    target: {value: 'chuck'},
  })
  fireEvent.change(screen.getByLabelText(/password/i), {
    target: {value: 'norris'},
  })

  fireEvent.click(screen.getByText(/submit/i))

  // just like a manual tester, we'll instruct our test to wait for the alert
  // to show up before continuing with our assertions.
  const alert = await screen.findByRole('alert')

  // .toHaveTextContent() comes from jest-dom's assertions
  // otherwise you could use expect(alert.textContent).toMatch(/congrats/i)
  // but jest-dom will give you better error messages which is why it's recommended
  expect(alert).toHaveTextContent(/congrats/i)
  expect(window.localStorage.getItem('token')).toEqual(fakeUserResponse.token)
})

test('handles server exceptions', async () => {
  // mock the server error response for this test suite only.
  server.use(
    rest.post('/api/login', (req, res, ctx) => {
      return res(ctx.status(500), ctx.json({message: 'Internal server error'}))
    }),
  )

  render(<Login />)

  // fill out the form
  fireEvent.change(screen.getByLabelText(/username/i), {
    target: {value: 'chuck'},
  })
  fireEvent.change(screen.getByLabelText(/password/i), {
    target: {value: 'norris'},
  })

  fireEvent.click(screen.getByText(/submit/i))

  // wait for the error message
  const alert = await screen.findByRole('alert')

  expect(alert).toHaveTextContent(/internal server error/i)
  expect(window.localStorage.getItem('token')).toBeNull()
})

We recommend using Mock Service Worker library to declaratively mock API communication in your tests instead of stubbing window.fetch, or relying on third-party adapters.

More Examples

We're in the process of moving examples to the docs site

You'll find runnable examples of testing with different libraries in the react-testing-library-examples codesandbox. Some included are:

You can also find React Testing Library examples at react-testing-examples.com.

Hooks

If you are interested in testing a custom hook, check out React Hooks Testing Library.

NOTE: it is not recommended to test single-use custom hooks in isolation from the components where it's being used. It's better to test the component that's using the hook rather than the hook itself. The React Hooks Testing Library is intended to be used for reusable hooks/libraries.

Guiding Principles

The more your tests resemble the way your software is used, the more confidence they can give you.

We try to only expose methods and utilities that encourage you to write tests that closely resemble how your React components are used.

Utilities are included in this project based on the following guiding principles:

  1. If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.
  2. It should be generally useful for testing individual React components or full React applications. While this library is focused on react-dom, utilities could be included even if they don't directly relate to react-dom.
  3. Utility implementations and APIs should be simple and flexible.

Most importantly, we want React Testing Library to be pretty light-weight, simple, and easy to understand.

Docs

Read The Docs | Edit the docs

Issues

Looking to contribute? Look for the Good First Issue label.

🐛 Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍 . This helps maintainers prioritize what to work on.

See Feature Requests

Questions

For questions related to using the library, please visit a support community instead of filing an issue on GitHub.

Contributors

Thanks goes to these people (emoji key):


Kent C. Dodds

💻 📖 🚇 ⚠️

Ryan Castner

📖

Daniel Sandiego

💻

Paweł Mikołajczyk

💻

Alejandro Ñáñez Ortiz

📖

Matt Parrish

🐛 💻 📖 ⚠️

Justin Hall

📦

Anto Aravinth

💻 ⚠️ 📖

Jonah Moses

📖

Łukasz Gandecki

💻 ⚠️ 📖

Ivan Babak

🐛 🤔

Jesse Day

💻

Ernesto García

💬 💻 📖

Josef Maxx Blake

💻 📖 ⚠️

Michal Baranowski

📝

Arthur Puthin

📖

Thomas Chia

💻 📖

Thiago Galvani

📖

Christian

⚠️

Alex Krolick

💬 📖 💡 🤔

Johann Hubert Sonntagbauer

💻 📖 ⚠️

Maddi Joyce

💻

Ryan Vice

📖

Ian Wilson

📝

Daniel

🐛 💻

Giorgio Polvara

🐛 🤔

John Gozde

💻

Sam Horton

📖 💡 🤔

Richard Kotze (mobile)

📖

Brahian E. Soto Mercedes

📖

Benoit de La Forest

📖

Salah

💻 ⚠️

Adam Gordon

🐛 💻

Matija Marohnić

📖

Justice Mba

📖

Mark Pollmann

📖

Ehtesham Kafeel

💻 📖

Julio Pavón

💻

Duncan L

📖 💡

Tiago Almeida

📖

Robert Smith

🐛

Zach Green

📖

dadamssg

📖

Yazan Aabed

📝

Tim

🐛 💻 📖 ⚠️

Divyanshu Maithani

📹

Deepak Grover

📹

Eyal Cohen

📖

Peter Makowski

📖

Michiel Nuyts

📖

Joe Ng'ethe

💻 📖

Kate

📖

Sean

📖

James Long

🤔 📦

Herb Hagely

💡

Alex Wendte

💡

Monica Powell

📖

Vitaly Sivkov

💻

Weyert de Boer

🤔 👀 🎨

EstebanMarin

📖

Victor Martins

📖

Royston Shufflebotham

🐛 📖 💡

chrbala

💻

Donavon West

💻 📖 🤔 ⚠️

Richard Maisano

💻

Marco Biedermann

💻 🚧 ⚠️

Alex Zherdev

🐛 💻

André Matulionis dos Santos

💻 💡 ⚠️

Daniel K.

🐛 💻 🤔 ⚠️ 👀

mohamedmagdy17593

💻

Loren ☺️

📖

MarkFalconbridge

🐛 💻

Vinicius

📖 💡

Peter Schyma

💻

Ian Schmitz

📖

Joel Marcotte

🐛 ⚠️ 💻

Alejandro Dustet

🐛

Brandon Carroll

📖

Lucas Machado

📖

Pascal Duez

📦

Minh Nguyen

💻

LiaoJimmy

📖

Sunil Pai

💻 ⚠️

Dan Abramov

👀

Christian Murphy

🚇

Ivakhnenko Dmitry

💻

James George

📖

João Fernandes

📖

Alejandro Perea

👀

Nick McCurdy

👀 💬

Sebastian Silbermann

👀

Adrià Fontcuberta

👀 📖

John Reilly

👀

Michaël De Boey

👀 💻

Tim Yates

👀

Brian Donovan

💻

Noam Gabriel Jacobson

📖

Ronald van der Kooij

⚠️ 💻

Aayush Rajvanshi

📖

Ely Alamillo

💻 ⚠️

Daniel Afonso

💻 ⚠️

Laurens Bosscher

💻

Sakito Mukai

📖

Türker Teke

📖

Zach Brogan

💻 ⚠️

Ryota Murakami

📖

Michael Hottman

🤔

Steven Fitzpatrick

🐛

Juan Je García

📖

Championrunner

📖

Sam Tsai

💻 ⚠️ 📖

Christian Rackerseder

💻

Andrei Picus

🐛 👀

Artem Zakharchenko

📖

Michael

📖

Braden Lee

📖

Kamran Ayub

💻 ⚠️

Matan Borenkraout

💻

Ryan Bigg

🚧

Anton Halim

📖

Artem Malko

💻

Gerrit Alex

💻

Karthick Raja

💻

Abdelrahman Ashraf

💻

Lidor Avitan

📖

Jordan Harband

👀 🤔

Marco Moretti

💻

sanchit121

🐛 💻

Solufa

🐛 💻

Ari Perkkiö

⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

Comments
  • [5.5.0] Getting warning about

    [5.5.0] Getting warning about "act" anyway

    Thanks for the fast work Kent, but seems something is still off. I've updated to 5.5.0 and tests are still generating same act warnings. Am I missing something here? Do we need to actually use act inside the tests?

    https://travis-ci.org/mobxjs/mobx-react-lite/builds/489613981

    It's curious that I've actually removed a bunch of flushEffects calls which were necessary before and tests are passing just fine. Clearly act helped with that. And yet those warnings shouldn't be there. 🤔

    released 
    opened by danielkcz 128
  • fix(typescript): move typings to DefinitelyTyped

    fix(typescript): move typings to DefinitelyTyped

    See #436, https://github.com/testing-library/dom-testing-library/pull/337

    Remove the TypeScript typedefs from this repo in favor of having the community maintain them at DefinitelyTyped.

    Why

    There are no core teammembers with the TS knowledge needed to maintain the types, and they are not well tested or integrated with the codebase.


    See also https://github.com/reduxjs/redux/issues/3500

    TypeScript released 
    opened by alexkrolick 96
  • feat: Add `renderHook`

    feat: Add `renderHook`

    What:

    Imlement minimal renderHook from @testing-library/react-hooks

    Why:

    @testing-library/react-hooks is not compatible with React 18 and it's questionable if certain APIs will make sense in React 18. This ensures that the supported version of React that is used with your Testing Library APIs is always consistent.

    error testing: We don't have this solved in @testing-library/react. It should be solved in the renderer testing library. suspense: Can be solved with wrapper waitForNextUpdate: Use waitFor instead. When an update is triggered and what is part of an update is not always clear and in 99% of the cases (even if hooks relying on data e.g. apollo-client) not relevant. See https://github.com/eps1lon/apollo-client/pull/1/

    How:

    Implement minimal renderHook with just rerender, rerender and unmount. Assertions are made on the committed result not the render result. Renders are not something to test for since they're ultimately not detereministic depending on the component implementation. However, we don't want to test component implementation details.

    For more granular testing one could always create a custom test component around the hook under test and pass it to our render. This has always been the recommended approach anyway. But it requires more writing and instead of insisting that this is bad practice we meet devs halfway, provide a render wrapper around creating a test component but then reduce the API of that render wrapper.

    If your goal was to count renders then React.Profiler is the better approach anyway.

    Checklist:

    • [x] Documentation added to the docs site: https://github.com/testing-library/testing-library-docs/pull/967
    • [x] Tests
    • [x] TypeScript definitions updated
    • [x] Ready to be merged
    enhancement released 
    opened by eps1lon 54
  • Support for React 18

    Support for React 18

    Describe the feature you'd like:

    It's probably premature, given experimental nature of Concurrent mode. but I might as we start the discussion.

    Perhaps I am misunderstanding something, but I think it would be useful if tests would run in Concurrent mode to mimic real app behavior as close as possible.

    At this point, it's probably about replacing ReactDOM.render with ReactDOM.createRoot.

    The question is how to make it in a compatible way so people can decide which version to use without polluting actual test files with it.

    Suggested implementation:

    Probably the most obvious choice is exposing function renderConcurrent which would be fine for the experimental phase. However, given that Concurrent will most likely become a "new normal" eventually, it would be kinda weird to have that in tests.

    Perhaps the env variable might be better approach ultimately. It's easy to switch and doesn't need to pollute actual test files with it.

    Describe alternatives you've considered:

    Publishing major version when Concurrent mode is official and stable and keep rolling in that direction only. An obvious drawback is that people would need to stick to the previous major as long as they are testing against code that doesn't support Concurrent mode.

    opened by danielkcz 42
  • on change for Material UI Select component not triggered

    on change for Material UI Select component not triggered

    • react-testing-library version: 4.1.3
    • react version: 16.4.1
    • node version: 11.10.1
    • npm (or yarn) version: 6.7.0

    Relevant code or config:

        const select = await waitForElement(() =>
          getByTestId("select-testid")
        );
    
        select.value = "testValue";
        fireEvent.change(select);
    
       <Select
           className={classes.select}
           onChange={this.handleSelectChange}
           value={selectedValue}
           inputProps={{
             id: "select-id",
             "data-testid": "select-id"
           }}
       >
    

    What you did:

    I am trying to fire the onChange method of the Material UI Select.

    What happened:

    onChange won't fire. Also tried with

    select.dispatchEvent(new Event('change', { bubbles: true }));
    
    opened by dimosmera 41
  • How to test React.Portal

    How to test React.Portal

    react-testing-library: 2.1.1 node: 8.9.3 yarn: 1.6.0

    import React from "react";
    import { render, Simulate } from "react-testing-library";
    
    import Button from "material-ui/Button";
    import Dialog, {
      DialogActions,
      DialogContent,
      DialogTitle
    } from "material-ui/Dialog";
    
    export const CommonDialog = props => {
      const { body, children, hideModal, isVisible, title } = props;
      return (
        <Dialog open={isVisible}>
          <DialogTitle>{title}</DialogTitle>
          <DialogContent>
            {body}
            {children}
          </DialogContent>
          <DialogActions>
            <Button id="close" onClick={hideModal}>
              Close
            </Button>
          </DialogActions>
        </Dialog>
      );
    };
    
    test("render dialog", () => {
      const mockCallback = jest.fn();
      const { getByText, getByTestId, container } = render(
        <CommonDialog title="test" isVisible={true} hideModal={mockCallback} />
      );
      Simulate.click(getByText("Close"));
      expect(mockCallback).toBeCalled();
      expect(container).toMatchSnapshot();
    });
    

    in the snapshot, it is just a simple div, and the Close button could not be found. It is not immediately not obvious what's went wrong here. I was using enzyme and it is working fine.

    question 
    opened by bugzpodder 40
  • Add getById method to render exports

    Add getById method to render exports

    Describe the feature you'd like:

    For many apps the labels of elements are subject to the most potential change and volatility. In many cases makes much more sense to reference by id f.ex when developing i18n apps.

    Suggested implementation:

    getByTestId a shortcut to container.querySelector([data-testid="${yourId}"])

    Simply add getById a shortcut to container.querySelector([id="${yourId}"])

    Teachability, Documentation, Adoption, Migration Strategy:

    Provide whatever docs to recommend it in some cases while not in others. I generally disagree with using text labels to reference HTML items as they are the most volatile in any app so it defeats the purpose IMO (+20 years web dev experience). But whatever rocks your boat.

    Cheers.

    opened by kristianmandrup 37
  • scheduleFn is calling NormalPriority as a function rather than cb

    scheduleFn is calling NormalPriority as a function rather than cb

    As of https://github.com/testing-library/react-testing-library/pull/732/files we're seeing:

    	TypeError: callback is not a function
    	    at <Jasmine>
    	    at scheduleFn (webpack:///node_modules/@testing-library/react/dist/@testing-library/react.esm.js:230:1 <- tests.webpack.js:27483:12)
    	    at scheduleCallback (webpack:///node_modules/@testing-library/react/dist/@testing-library/react.esm.js:232:1 <- tests.webpack.js:27485:46)
    	    at Object.then (webpack:///node_modules/@testing-library/react/dist/@testing-library/react.esm.js:245:1 <- tests.webpack.js:27498:9)
    

    Looking at that PR it seems to have two sources of truth: isModernScheduleCallbackSupported based on the react version and NormalPriority based on the existence of Scheduler.

    isModernScheduleCallbackSupported seems to be true yet Scheduler undefined.

    Which causes it to call scheduleFn(NormalPriority, cb) rather than scheduleFn(cb). And scheduleFn is callback => callback().

    released 
    opened by lerouxb 35
  • Add getById and getByClass

    Add getById and getByClass

    Querying by id and classes is the Hello World of the frontend querying and the library doesn't allow that for now.

    What about creating the getById and getByClass on the tests?

    Restricting the frontend id querying is not improving, it is quite the opposite, what is really does is decrease the capacity of the library.

    Placing a lot of data-testids on the code pollutes it, because it places unnecessary tags on html codes in terms of code functionality. The code becomes polluted with tags only related for testing.

    I am in favor of TDDs, but adding things in the code (or worse: on html tags) only for testing is exaggerated. A good TDD will improve the code with more organization! A bad TDD will add things on code only related for testing purposes.

    Some people can argue and defend the usage of data-testids on the code for whatever reason, but what I find uncomfortable is to disable for everybody the most basic querying on DOM elements.

    opened by Victorcorcos 34
  • Fix build for React next

    Fix build for React next

    Not sure exactly how/when this happened, but the build is failing: https://travis-ci.org/github/testing-library/react-testing-library/builds/703268660

    Help welcome!

    bug released 
    opened by kentcdodds 33
  • useEffect not triggering inside jest

    useEffect not triggering inside jest

    • react-testing-library version: 5.2.3
    • react version: 16.7.0-alpha.0
    • node version: CodeSandbox
    • npm (or yarn) version: CodeSandbox

    Relevant code or config:

      let a = false;
      function Test() {
        React.useEffect(() => {
          a = true;
        });
        return <div>Hello World</div>;
      }
      render(<Test />);
      expect(a).toBe(true);
    

    What you did:

    I'm trying to test functions with the useEffect hook inside jest.

    What happened:

    The useEffect hook is not executed correctly inside a jest environment after calling render(<Test />). However it appears to be working correctly if it is called directly in a browser environment.

    Reproduction:

    Working example: https://codesandbox.io/s/l947z8v6xq (index.js) Not working example in jest: https://codesandbox.io/s/7k5oj92740 (index.test.js)

    Problem description:

    The useEffect hook should have been executed after the render call

    enhancement 
    opened by peterjuras 32
  • FakeTimes problem when upgrading jest 25 to 29

    FakeTimes problem when upgrading jest 25 to 29

    Hi, everyone! I have several problems when upgrading jest 25 to 29 (Problem on faketimers)

    Installed dependencies

    "react": "16.13.1", "react-dom": "16.13.1",

    "@testing-library/react-hooks": "^7.0.2", "@testing-library/jest-dom": "5.16.5", "@testing-library/react": "12.1.5", "@types/jest": "28.1.1", "@types/react": "^17.0.33", "jest": "29.2.2", "jest-environment-jsdom": "^29.2.2", "jest-junit": "^12.0.0", "typescript": "4.3"

    Jest.config image

    When using fake timers i have to set legacy to true and the advanceTimers going to works, but it's not work in another test Example :

    image On this code advanceTimers not works fine, at some cases there are a few tests that we need to raise the timeout duration, is there any explanation or something ?

    image If you have any suggestions for my problem, it's going to help me a lot. Thank you

    opened by Okyaaa 0
  • getByText not working for multiline text

    getByText not working for multiline text

    Using multiline text in getByText fails. Is there a workaround for this?

    Failing test

    const exampleText = `
    hello
    
    world
    `
    
    const textElement = screen.getByText(
      exampleText.slice(0, 10),
      { exact: false }
    );
    console.info(textElement.textContent === exampleText); // == True
    expect(screen.getByText(exampleText)).toBeInTheDocument(); // == Fail
    

    Passing test

    const exampleText = `hello world`
    
    const textElement = screen.getByText(
      exampleText.slice(0, 10),
      { exact: false }
    );
    console.info(textElement.textContent === exampleText); // == True
    expect(screen.getByText(exampleText)).toBeInTheDocument(); // == Pass
    
    opened by sbland 1
  • issue in react testing library + MSW+ Redux + Thunk

    issue in react testing library + MSW+ Redux + Thunk

    Hello facing issue in react testing library + MSW+ Redux + Thunk

    Could you please check All details https://github.com/reduxjs/react-redux/issues/1975

    opened by nitinmagdumvista 0
  • Filter by description on findByLabel for password input tests

    Filter by description on findByLabel for password input tests

    Is your feature request related to a problem? Please describe.

    I am trying to test that the inputs in my form have correct inline validation errors set as aria descriptions. This works great when the input is simply a textbox:

    <Label>
      Email
      <input type="text' aria-describedby="emailError" />
    </Label>
    <div id="emailError">Please enter a valid email address</div>
    
    ...
    
    expect(findbyRole('textbox', {
        name: 'Email',
        description: 'Please enter a valid email'
    })).toBeInTheDocument();
    

    However, when the input is a password since it has no role I cannot use the description field on getByRole to find the element.

    Describe the solution you'd like

    This issue recommends using getByLabelText for password inputs, so it would be a lot easier if that query could also search by description.

    <Label>
      Password
      <input type="password' aria-describedby="passwordError" />
    </Label>
    <div id="passwordError">Please enter your password</div>
    
    ...
    
    expect(findByLabelText('Password', {
        description: 'Please enter your password'
    })).toBeInTheDocument();
    

    Describe alternatives you've considered

    Alternatively, if react-testing library could do some magic that means findByRole('password') just works, then that would be a very simple solution and most users probably wouldn't event have to think about it.

    For now my tests merely assert that the error exists in the page and ignore the describedby connection.

    expect(await screen.findByText('Please enter your new password')).toBeInTheDocument();
    

    Additional context Add any other context or screenshots about the feature request here.

    opened by e-compton 1
  • act() now return always a Promise

    act() now return always a Promise

    Description

    Today I update my work project deps, and I noticed that the eslint throws me an error.

    image

    At the beginning I thought that was my mistake, but I checked the code and I found that the error was dispatch because I'm calling act(() => mycode()) as as sync code. I never had this problem before, so I checked my updated types, and I found this export const act: typeof reactAct extends undefined ? (callback: () => void) => void : typeof reactAct, nothing change on testing-library types, but, react-dom updated their types,

    export function act<T>(callback: () => T | Promise<T>): Promise<T>; export function act(callback: () => VoidOrUndefinedOnly): Promise<void>

    on previous versions act had this types

    export function act(callback: () => Promise<void>): Promise<undefined>; export function act(callback: () => VoidOrUndefinedOnly): void;

    Now my question, Will change the act type on testing-library or not?, act is still necessary if we already have the waitFor function?

    Versions

    • react 18.2.0
    • react-dom 18.2.0
    • @types/react 18.0.23 -> 18.0.25
    • @types/react-dom 18.0.7 -> 18.0.9
    • @testing-library/react 13.14.0
    • @testing-library/user-event 14.4.3
    opened by GOI17 4
  • Support `beforeInput` event

    Support `beforeInput` event

    Describe the feature you'd like:

    fireEvent support beforeInput event

    Suggested implementation:

    N/A

    Describe alternatives you've considered:

    N/A

    Teachability, Documentation, Adoption, Migration Strategy:

    N/A

    needs more information 
    opened by zombieJ 2
Releases(v13.4.0)
Owner
Testing Library
The home for all testing-library projects
Testing Library
JavaScript Testing utilities for React

Enzyme Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse,

enzyme - JavaScript Testing utilities for React 20k Dec 28, 2022
A complete habits manager, where you can track your progress and complete each daily activity in an organized way.

TrackIt Habit manager in a dynamic, clear and simple way. TackIt is an application that seeks to make it simple and accessible for any user to control

Rui Neto 13 Dec 31, 2022
a more intuitive way of defining private, public and common routes for react applications using react-router-dom v6

auth-react-router is a wrapper over react-router-dom v6 that provides a simple API for configuring public, private and common routes (React suspense r

Pasecinic Nichita 12 Dec 3, 2022
:fire: A highly scalable, offline-first foundation with the best developer experience and a focus on performance and best practices.

Start your next react project in seconds A highly scalable, offline-first foundation with the best DX and a focus on performance and best practices Cr

react-boilerplate 28.9k Jan 6, 2023
This app will share good first issues.

catsup A GitHub App built with Probot that This app alerts you of good first issues. Setup # Install dependencies npm install # Run the bot npm start

Open Sauced 6 Dec 5, 2022
A complete set up of the React application with Typescript, Webpack 5, Babel v7, SSR, Code Splitting and HMR.

Getting Started with react-final-boilerplate Clone the code npm install You are good to go with React Application. Open http://localhost:3000/ and you

null 24 Dec 22, 2022
This website was designed to allow viewers complete access to all movie and tv series trailers. It was created using React + MUI

Trailer - Time ?? Demo https://trailer-time.netlify.app/ ?? about This project is a simplified front end clone of some movie webside (like Netflix/Hul

null 9 Aug 24, 2022
A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles.

A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles. If you're tired of fighting some other developer's CSS and DOM structure, this carousel is for you.

Vladimir Bezrukov 1 Dec 24, 2021
Utilities library built on top of Next.js providing feature extensions and helpers for common patterns

nextjs-utilites This library provides many helpful utilities for use in Next.js projects. Prerequisites This project requires NodeJS (version 8 or lat

Snehil K 5 Sep 7, 2022
A collection of framework specific Auth utilities for working with Supabase.

A collection of framework specific Auth utilities for working with Supabase.

Supabase Community 507 Jan 2, 2023
Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones.

Stitches Mix Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones. Usage To import al

João Pedro Schmitz 12 Aug 8, 2022
React + Redux starter kit / boilerplate with Babel, hot reloading, testing, linting and a working example app built in

A comprehensive starter kit for rapid application development using React. Why Slingshot? One command to get started - Type npm start to start develop

Cory House 9.8k Dec 22, 2022
⚡️ Look for Covid-19 Resources, Get Vaccine Availability Notification, Complete source code for covidrescue.co.in website.

covidrescue.co.in ⚡️ Get real-time, verified leads on Oxygen, Remdesivir, ICU, Beds, Food and more based on your location. Get notifications on Vaccin

Placeholder Tech 15 Jul 10, 2022
Web application that consumes an API to provide an complete experience of an recipes app

Project: Recipes App Project developed studying in Trybe. Technologies and tools used React React Hooks Context API SCRUM / Kanban Project objective T

Ádran Farias Carnavale 0 Jun 14, 2022
A complete example of fullstack NFT minting dApp

This a complete example of fullstack NFT minting dApp. BoredApe is built with the purpose of providing an entry point for future NFT Minting Website projects.

codingwithdidem 66 Dec 13, 2022
A checklist for you to complete as you go through Elden Ring.

Elden Ring Checklist A checklist for you to complete as you go through Elden Ring. Visit the website · Report Bug · Request Feature Table of Contents

Griffin Strayer 23 Dec 23, 2022
Library to build UI based on virtual DOM

vidom Vidom is just a library to build UI. It's highly inspired from React and based on the same ideas. Its main goal is to provide as fast as possibl

Filatov Dmitry 415 Nov 20, 2022
🦁 <1kb compiler-augmented virtual DOM. It's fast!

English | 中文 <1kb compiler-augmented virtual DOM. It's fast! Current Virtual DOM implementations are inadequate—Ranging from overcomplicated to abando

Aiden Bai 5.5k Jan 5, 2023
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.

Recoil · Recoil is an experimental set of utilities for state management with React. Please see the website: https://recoiljs.org Installation The Rec

Facebook Experimental 18.2k Jan 8, 2023