react-testing-library | 🐐 Simple and complete React DOM testing utilities that encourage good testing practices | Testing library

 by   testing-library JavaScript Version: v14.0.0 License: MIT

kandi X-RAY | react-testing-library Summary

kandi X-RAY | react-testing-library Summary

react-testing-library is a JavaScript library typically used in Testing, React, Jest applications. react-testing-library has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i temporal-testing-library-react-concurrent' or download it from GitHub, npm.

Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs.
Support
    Quality
      Security
        License
          Reuse

            kandi-support Support

              react-testing-library has a medium active ecosystem.
              It has 17907 star(s) with 1073 fork(s). There are 140 watchers for this library.
              OutlinedDot
              It had no major release in the last 12 months.
              There are 26 open issues and 675 have been closed. On average issues are closed in 35 days. There are 2 open pull requests and 0 closed requests.
              It has a neutral sentiment in the developer community.
              The latest version of react-testing-library is v14.0.0

            kandi-Quality Quality

              react-testing-library has 0 bugs and 0 code smells.

            kandi-Security Security

              react-testing-library has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
              react-testing-library code analysis shows 0 unresolved vulnerabilities.
              There are 0 security hotspots that need review.

            kandi-License License

              react-testing-library is licensed under the MIT License. This license is Permissive.
              Permissive licenses have the least restrictions, and you can use them in most projects.

            kandi-Reuse Reuse

              react-testing-library releases are available to install and integrate.
              Deployable package is available in npm.
              Installation instructions, examples and code snippets are available.

            Top functions reviewed by kandi - BETA

            kandi has reviewed react-testing-library and discovered the below as its top functions. This is intended to give you an instant insight into react-testing-library implemented functionality, and help decide if they suit your requirements.
            • Main render function
            • Render container elements into a container .
            • Sets up the actions environment for the given function .
            • Creates a Container instance .
            • React to render hooks
            • Gets the global instance object .
            • Create a React root root object .
            • Removes all root entries .
            • Initialize a new React component
            • The base implementation of rerender .
            Get all kandi verified functions for this library.

            react-testing-library Key Features

            No Key Features are available at this moment for react-testing-library.

            react-testing-library Examples and Code Snippets

            Complex Example
            npmdot img1Lines of Code : 135dot img1no licencesLicense : No License
            copy iconCopy
            // 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.prev  
            Test Utilities
            JavaScriptdot img2Lines of Code : 82dot img2no licencesLicense : No License
            copy iconCopy
            module.exports = {
              foo: {
                type: 'string',
                description: '...',
                testValue: 'value',
              },
              bar: {
                type: 'object',
                description: '...',
                properties: {
                  baz: {
                    type: 'string',
                    testValue: 'value',
                  },
                  
            Basic Example
            npmdot img3Lines of Code : 47dot img3no licencesLicense : No License
            copy iconCopy
            // 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 [sho  
            ReferenceError: expect is not defined when using @testing-library/react
            JavaScriptdot img4Lines of Code : 13dot img4License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            setupFilesAfterEnv: [
              './setupTests.js',
            ],
            
            import React from 'react';
            import App from './App';
            import {render, fireEvent, waitFor, screen} from '@testing-library/react'
            
            test('renders learn react link',async () 
            React Testing Library + Material UI (v4) Hidden component
            JavaScriptdot img5Lines of Code : 21dot img5License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            import { render, screen } from '@testing-library/react'
            import Greet from './Greet'
            import { MuiThemeProvider } from '@material-ui/core';
            import { createTheme } from '@material-ui/core/styles'
            const theme = createTheme({ props: { MuiWithWi
            Redux-mock-store: Cannot get all dispatched actions into mocked store
            JavaScriptdot img6Lines of Code : 27dot img6License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            import {waitFor} from '@testing-library/react'
            
            it('Test can dispatch success actions', async () => {
                mock.onGet('http://localhost:8000/api/v1' + baseUrl).reply(200);
                store.dispatch(pingActions.fetchItems());
            
                expect(store.g
            What's the proper typing for a React Testing Library wrapper in typescript?
            TypeScriptdot img7Lines of Code : 19dot img7License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            import { ReactElement } from 'react'
            import { render as rtlRender } from '@testing-library/react'
            import { QueryClientProvider, QueryClient } from 'react-query'
            
            const queryClient = new QueryClient();
            
            const render = (ui: ReactElement, { c
            Timed out in waitForElementToBeRemoved error in RTL
            JavaScriptdot img8Lines of Code : 46dot img8License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            import { render, screen, waitFor } from '@testing-library/react'
            import userEvent from '@testing-library/user-event'
            import React from 'react'
            
            import Login from './../pages/login'
            
            describe('Login Page', () => {
              it('renders without c
            Why is my header component defined but never used in my test?
            JavaScriptdot img9Lines of Code : 10dot img9License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            import React from 'react'
            import Header from './Header'
            import {render} from '@testing-library/react'
            
            test("Renders's the header and required inputs", () => {
             const { getByText, getByTestId } = render();
              expect(getByTestId("header")
            React jest mocking useAuth0 Cannot destructure property 'isLoading' of undefined
            JavaScriptdot img10Lines of Code : 38dot img10License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            // test-utils.js
            import React from 'react'
            import { render as rtlRender } from '@testing-library/react'
            import { createStore } from 'redux'
            import { Provider } from 'react-redux'
            import { MockedProvider } from '@apollo/client/testing';
            imp

            Community Discussions

            QUESTION

            Test was not wrapped in act(...)
            Asked 2022-Apr-01 at 04:30

            I am running into a strange issue, would appreciate help here. I followed the example from here, can't tell what the heck is going on. The warning shouldn't be showing up, right?

            Component: Hello.tsx

            ...

            ANSWER

            Answered 2022-Apr-01 at 04:30

            The test example in the codesandbox passes without warning. You forgot to use await screen.findByText(/loaded/i). The findBy Queries:

            findBy methods are a combination of getBy queries and waitFor

            findBy queries work when you expect an element to appear but the change to the DOM might not happen immediately.

            For testing the async code, you need to wait for the state update to be applied. So you need to use waitFor or findBy queries.

            findBy queries use waitFor underly, see makeFindQuery

            Source https://stackoverflow.com/questions/71701591

            QUESTION

            React Testing Library with userEvent.click wrong act() warning
            Asked 2022-Mar-31 at 18:50

            I have several tests written with Jest and React Testing Library. They all mock fetch and use a userEvent.click call to fire a submit button which makes a fetch request. State gets updated in the component and I make my assertions. I am using a useEffect hook to populate a data array but it only runs on initial load given that I'm passing an empty dependency array to it. All of my tests currently pass. If I run them all together, I get a wrong act() error that stems from useEffect:

            ...

            ANSWER

            Answered 2022-Mar-31 at 18:41

            I was finally able to track down a workaround. This GitHub post mentions wrapping userEvent() calls in act() which I've already done. The workaround to the Warning: It looks like you're using the wrong act() around your test interactions. console error is to add the following code just after the userEvent() call and before the assertions:

            Source https://stackoverflow.com/questions/71681055

            QUESTION

            Failing tests because of the daylight saving time change
            Asked 2022-Mar-31 at 12:45

            I have tests where Im using getByText function in react-testing-library. Im looking for element in DOM that has value "10-10-2020 12:00". But after daylight saving time change, all my tests have failed because due to the change, the display text has changed to "10-10-2020 13:00" (one hour forwards) and now Im not able to get those elements. I will have to update my tests, but they will obviously fail once again when the time is changed in winter.

            It happens because e.g. new Date('2020-01-01T00:00:00.000Z') returns 01 01 2020 01:00:00 instead of 01 01 2020 00:00:00 because of the timezones.

            Is there any workaround or fix to make my tests resistant to daylight saving time change and timezones?

            ...

            ANSWER

            Answered 2022-Mar-31 at 12:45

            Setting the hardcoded date and time for jest should help:

            Source https://stackoverflow.com/questions/71692539

            QUESTION

            How to write a test with Jest and React testing library to check if anchor-tag exist
            Asked 2022-Mar-07 at 13:26

            Based on a prop anchor I am rendering a Material ui button or a React router (anchor) link:

            ...

            ANSWER

            Answered 2022-Mar-07 at 13:26
            it('should render anchor button', () => {
                const { container } = mount(Test);
                expect(container.getByText('Test').closest('a')).toBeInTheDocument()
              });
            

            Source https://stackoverflow.com/questions/71381737

            QUESTION

            Reproducable asynchronous bug found in @testing-library/react
            Asked 2022-Mar-01 at 09:31

            Unless I'm mistaken, I believe I've found a bug in how rerenders are triggered (or in this case, aren't) by the @testing-library/react package. I've got a codesandbox which you can download and reproduce in seconds:

            https://codesandbox.io/s/asynchronous-react-redux-toolkit-bug-8sleu4?file=/README.md

            As a summary for here, I've just got a redux store and I toggle a boolean value from false to true after some async activity in an on-mount useEffect in a component:

            ...

            ANSWER

            Answered 2022-Mar-01 at 09:31

            I've apparently misunderstood how react-testing-library works under the hood. You don't even need to use rerender or act at all! Simply using a waitFor with await / async is enough to trigger the on mount logic and subsequent rendering:

            Source https://stackoverflow.com/questions/71259493

            QUESTION

            react - how to test a component if it has value prop
            Asked 2022-Feb-28 at 10:35

            App.js

            ...

            ANSWER

            Answered 2022-Feb-28 at 10:35

            With react-testing-library you want to avoid testing the internal values of components.
            Instead you should be checking if the html that's rendered is correct.

            In your example: rather than checking whether the value prop is correct, you should check that given a certain value (e.g. "Test Value") the input html element contains the text "Test Value".

            Reference: https://testing-library.com/docs/guiding-principles

            Source https://stackoverflow.com/questions/71293549

            QUESTION

            screen.getByText is not a function
            Asked 2022-Feb-21 at 13:32

            I am using jest with react-testing-library for the most part without issues until I started to move to the screen > getByText/etc way of testing.

            Test ...

            ANSWER

            Answered 2022-Feb-21 at 13:32
            import { screen, configure } from '@testing-library/react'
            

            Source https://stackoverflow.com/questions/71204793

            QUESTION

            FE: Unit testing window.location.href changing on button click (test fails)
            Asked 2022-Feb-10 at 00:57

            I am trying to test when the window.location.href changes after a button is clicked using react-testing-library. I have seen examples online where you manually update window.location.href inside of a test case as so window.location.href = 'www.randomurl.com' and then follow it with expect(window.location.href).toEqual(www.randomurl.com). While this indeed will pass, I want to avoid this as I'd rather simulate the user actions instead of injecting the new value into the test. If I do that, even if I remove my button click (which is what will actually trigger the function call) the expect will still pass because I have anyway manually updated the window.location.href in my test

            What I've opted for is having goToThisPage func (which will redirect the user) to be placed outside of my functional component. I then mock goToThisPage in my test file and in my test case check whether it has been called. I do know that the goToThisPage is being triggered because I included a console.log and when I run my tests I see it in my terminal. Nonetheless, the test still fails. I have been playing around with both spyOn and jest.doMock/mock with no luck

            component.js

            ...

            ANSWER

            Answered 2022-Feb-08 at 09:09

            You exporting both functions and then defining a default export of the Component itself is what's causing the problem (which is mixing up default and named exports).

            Remove export default Component; and change the top import in your test file to import {Component, goToThisPage} from './component'. That said I'm not sure you even need to export goToThisPage (for the Jest test at least).

            Source https://stackoverflow.com/questions/71021835

            QUESTION

            Difference between MemoryRouter and Router concerning testing with react-testing-library
            Asked 2022-Jan-29 at 11:55

            I work on a small App to get familiar with testing and such in React, using jest and React-Testing-Library.

            In my Component, I have a Routes with two Route. One of those looks like this:

            } />

            If the user is not logged in, redirects the user to a Login /> Component via .

            This is just for context. All of this works. But for quite some time, I couldnt make the test pass to check that the Navigation happens. I figured, that my problem was the Route method I used in React-Testing-Librariesrender() method. The test passes if I use but doesnt if I wrap in ..

            In the following stackblitz, I have implemented both versions. The one that s not working, is currently commented out. Could someone tell me, why it only works with MemoryRouter? You find the test in src/routing.test.tsx. You can run the tests with npm run test. https://stackblitz.com/edit/github-nfj4lw?file=src/routes.test.tsx

            ...

            ANSWER

            Answered 2022-Jan-29 at 11:55

            The Router is a low level function that is not environment specific. As the docs state, you probably never want to render your components with it. Replacing it with higher level environment aware functions like BrowserRouter or (MemoryRouter) makes your test pass:

            Source https://stackoverflow.com/questions/70904665

            QUESTION

            Best way to test a text in a div or p tag in react-testing-library
            Asked 2022-Jan-14 at 02:39

            What is the best way to test a text in a div or a p tag in react-testing-library ?

            Let's pretend that we have a react component as such :

            ...

            ANSWER

            Answered 2022-Jan-14 at 02:39

            The difference between .toBeInTheDocument() and .toBeVisible() are explained clearly in the doc.

            In short: An element can be present in the document but not visible to the user.

            E.g.

            Source https://stackoverflow.com/questions/70700684

            Community Discussions, Code Snippets contain sources that include Stack Exchange Network

            Vulnerabilities

            No vulnerabilities reported

            Install react-testing-library

            This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:. for installation via yarn. 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.

            Support

            Please file an issue for bugs, missing documentation, or unexpected behavior.
            Find more information at:

            Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items

            Find more libraries
            CLONE
          • HTTPS

            https://github.com/testing-library/react-testing-library.git

          • CLI

            gh repo clone testing-library/react-testing-library

          • sshUrl

            git@github.com:testing-library/react-testing-library.git

          • Stay Updated

            Subscribe to our newsletter for trending solutions and developer bootcamps

            Agree to Sign up and Terms & Conditions

            Share this Page

            share link