ChatGPT解决这个技术问题 Extra ChatGPT

How do you test for the non-existence of an element using jest and react-testing-library?

I have a component library that I'm writing unit tests for using Jest and react-testing-library. Based on certain props or events I want to verify that certain elements aren't being rendered.

getByText, getByTestId, etc throw and error in react-testing-library if the element isn't found causing the test to fail before the expect function fires.

How do you test for something not existing in jest using react-testing-library?

I mean the fact this question had this much popularity speaks about how intuitive the API is.

k
kentcdodds

From DOM Testing-library Docs - Appearance and Disappearance

Asserting elements are not present The standard getBy methods throw an error when they can't find an element, so if you want to make an assertion that an element is not present in the DOM, you can use queryBy APIs instead: const submitButton = screen.queryByText('submit') expect(submitButton).toBeNull() // it doesn't exist The queryAll APIs version return an array of matching nodes. The length of the array can be useful for assertions after elements are added or removed from the DOM. const submitButtons = screen.queryAllByText('submit') expect(submitButtons).toHaveLength(2) // expect 2 elements not.toBeInTheDocument The jest-dom utility library provides the .toBeInTheDocument() matcher, which can be used to assert that an element is in the body of the document, or not. This can be more meaningful than asserting a query result is null. import '@testing-library/jest-dom/extend-expect' // use `queryBy` to avoid throwing an error with `getBy` const submitButton = screen.queryByText('submit') expect(submitButton).not.toBeInTheDocument()


My bad kentcdodds, thank you. I used getByTestId and got the same error. And, I didn't check the FAQ, sorry. Great library! Can you modify your answer to include the `.toBeNull();
I believe the link above was meant to point to the react-testing-library docs
The new docs site was published a few days ago. I should have used a more permanent link. Thanks for the update @pbre!
and queryByText for those who want the equivalent to getByText that is null safe
S
Sam

Use queryBy / queryAllBy.

As you say, getBy* and getAllBy* throw an error if nothing is found.

However, the equivalent methods queryBy* and queryAllBy* instead return null or []:

queryBy queryBy* queries return the first matching node for a query, and return null if no elements match. This is useful for asserting an element that is not present. This throws if more than one match is found (use queryAllBy instead). queryAllBy queryAllBy* queries return an array of all matching nodes for a query, and return an empty array ([]) if no elements match.

https://testing-library.com/docs/dom-testing-library/api-queries#queryby

So for the specific two you mentioned, you'd instead use queryByText and queryByTestId, but these work for all queries, not just those two.


This is way better than the accepted answer. Is this API newer?
Thanks for the kind words! This is basically the same functionality as the accepted answer, so I don't think it's a newer API (but I could be wrong). The only real difference between this answer and the accepted one is that the accepted answer says that there's only method which does this (queryByTestId) when in fact there are two whole sets of methods, of which queryByTestId is one specific example.
Thanks I'd much prefer this than setting test-ids
Thank you for that detailed explanation. It's a such a subtle difference that I didn't see it despite looking at their example here: github.com/testing-library/jest-dom#tobeinthedocument :face-palm:
G
Gabriel Vasile

getBy* throws an error when not finding an elements, so you can check for that

expect(() => getByText('your text')).toThrow('Unable to find an element');

This can be pretty error-prone. Error throws are used for debugging purposes and not to for verifcation.
This worked in my case but, only after using arrow function. Can you please let me know why we need it? It does not work without it.
V
Valentin Garreau

You have to use queryByTestId instead of getByTestId.

Here a code example where i want to test if the component with "car" id isn't existing.

 describe('And there is no car', () => {
  it('Should not display car mark', () => {
    const props = {
      ...defaultProps,
      base: null,
    }
    const { queryByTestId } = render(
      <IntlProvider locale="fr" messages={fr}>
        <CarContainer{...props} />
      </IntlProvider>,
    );
    expect(queryByTestId(/car/)).toBeNull();
  });
});

D
DHIRENDRA SINGH
const submitButton = screen.queryByText('submit')
expect(submitButton).toBeNull() // it doesn't exist

expect(submitButton).not.toBeNull() // it exist

m
matrixb0ss

Worked out for me (if you want to use getByTestId):

expect(() => getByTestId('time-label')).toThrow()

N
Nikola Jovanović

Another solution: you could also use a try/catch block

expect.assertions(1)
try {
    // if the element is found, the following expect will fail the test
    expect(getByTestId('your-test-id')).not.toBeVisible();
} catch (error) {
    // otherwise, the expect will throw, and the following expect will pass the test
    expect(true).toBeTruthy();
}

This will work, by Jest will warn you of "Avoid calling expect conditionally" (jest/no-conditional-expect)
A
Andy Rich

You can use react-native-testing-library "getAllByType" and then check to see if the component is null. Has the advantage of not having to set TestID, also should work with third party components

 it('should contain Customer component', () => {
    const component = render(<Details/>);
    const customerComponent = component.getAllByType(Customer);
    expect(customerComponent).not.toBeNull();
  });

This kind of breaches the premise of not having implementation details (such as the component name) in the test.
M
Metacoder

I recently wrote a method to check visibility of element for a jest cucumber project.

Hope it is useful.

public async checknotVisibility(page:Page,location:string) :Promise<void> 
{
    const element = await page.waitForSelector(location);
    expect(element).not.toBe(location); 
}