react-testing-library why is toBeInTheDocument() not a function

后端 未结 5 1093
别跟我提以往
别跟我提以往 2021-02-11 15:35

Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.

 it(\'should sho         


        
相关标签:
5条回答
  • 2021-02-11 15:42

    When you do npm i @testing-library/react make sure there is a setupTests.js file with the following statement in it

    import '@testing-library/jest-dom/extend-expect';

    0 讨论(0)
  • 2021-02-11 15:46

    As mentioned by Giorgio, you need to install jest-dom. Here is what worked for me:

    (I was using typescript)

    npm i --save-dev @testing-library/jest-dom
    

    Then add an import to your setupTests.ts

    import '@testing-library/jest-dom/extend-expect';
    

    Then in your jest.config.js you can load it via:

    "setupFilesAfterEnv": [
        "<rootDir>/src/setuptests.ts"
      ]
    
    
    
    0 讨论(0)
  • 2021-02-11 15:51

    toBeInTheDocument is not part of RTL. You need to install jest-dom to enable it.

    0 讨论(0)
  • 2021-02-11 15:55

    If you don't already have jest-dom installed, you need to install it using the command below.

    npm i --save-dev @testing-library/jest-dom
    

    create a file in the root of your project folder and name it jest-setup.js. Your file should have the following content.

    import "@testing-library/jest-dom/extend-expect";
    

    In your package.json, add the code below to your jest config;

    "jest": {
        "setupFilesAfterEnv": ["<rootDir>/jest-setup.js"]
    }
    
    0 讨论(0)
  • 2021-02-11 15:56

    Instead of doing:

        expect(queryByText('test')).toBeInTheDocument()
    

    you can find and test that it is in the document with just one line by using

        let element = getByText('test');
    

    The test will fail if the element isn't found with the getBy call.

    0 讨论(0)
提交回复
热议问题