488

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?

1
  • 14
    I mean the fact this question had this much popularity speaks about how intuitive the API is. Commented May 10, 2022 at 14:29

14 Answers 14

810

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()
Sign up to request clarification or add additional context in comments.

14 Comments

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
|
104

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.

5 Comments

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:
I needed to know how to do this for getByTestId since that is what I want to key off of. I was not aware that they had a queryByTestId which would have taken me at least another query on DuckDuckGo and who knows how much additional time to find a proper solution. Mucho Graciaaahhh!
90

Hope this will be helpfull

this table shows why/when function errors

which functions are asynchronous

what is return statement for function

enter image description here

4 Comments

This can help me, I use queryByTestId() and check with toBeNull()
The queryBy matchers are what I always use for testing if something doesn't exist. For example, the assertion expect(queryByTestId('some-button')).notToBeInTheDocument() will pass if that button is not rendered.
Arigato/Dankeschön/Thanks. Read more and probably image ref
Please add the source link so that others can understand whether this is up-to-date
38

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');

3 Comments

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.
@RahulMahadik because expect(...) will call the anonymous function when it's ready to detect/catch a thrown error. If you omit the anonymous arrow function, you will immediately call a throwing function as the code executes, which immediately breaks out of execution.
34
const submitButton = screen.queryByText('submit')
expect(submitButton).toBeNull() // it doesn't exist

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

2 Comments

This should be the accepted answer. Unlike getBy* and findBy* methods, queryBy* does not throw an error if the item is not found. It simply returns null.
I think it depends on your use case, if you need async side effects to settle then using a solution like findBy with expects to throw should be better I think?
31

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();
  });
});

Comments

26

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

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

Comments

13

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();
}

EDIT:

I found a one-line alternative:

expect(screen.queryByTestId("your-test-id")).not.toBeInTheDocument();

2 Comments

This will work, by Jest will warn you of "Avoid calling expect conditionally" (jest/no-conditional-expect)
You can also use expect(findByTestId('your-test-id')).rejects.toThrow(); since the promise-based findByTestId() will reject when the element is not found upon awaiting. expect(promise).rejects.toThrow() will await the promise and pass the test when the promise rejects due to a thrown exception.
8

The default behavior of queryByRole is to find exactly one element. If not, it throws an error. So if you catch an error, this means the current query finds 0 element

expect(
   ()=>screen.getByRole('button')
).toThrow()

getByRole returns 'null', if it does not find anthing

 expect(screen.queryByRole('button')).toEqual((null))

findByRole runs asynchronously, so it returns a Promise. If it does not find an element, it rejects the promise. If you are using this, you need to run async callback

test("testing", async () => {
  let nonExist = false;
  try {
    await screen.findByRole("button");
  } catch (error) {
    nonExist = true;
  }
  expect(nonExist).toEqual(true);
});
    

Comments

3

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();
  });

1 Comment

This kind of breaches the premise of not having implementation details (such as the component name) in the test.
3
// check if modal can be open
const openModalBtn = await screen.findByTestId("open-modal-btn");
fireEvent.click(openModalBtn);

expect(
  await screen.findByTestId(`title-modal`)
).toBeInTheDocument();


// check if modal can be close
const closeModalBtn = await screen.findByTestId(
  "close-modal-btn"
);
fireEvent.click(closeModalBtn);

export const sleep = (ms: number) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

export const pause = async (ms?: number) => {
  await act(async () => {
    await sleep(ms || 100);
  });
};


const Way1 = async ()=>{
  await pause();
  expect(screen.queryByTestId("title-modal")).toBeNull();
}
const Way2 = async ()=>{
  let error = false
  try{
    await screen.findByTestID("title-modal")
  } catch (e) {
    error = true
  }
  expect(error).toEqual(true)
}

when you use findByTestId function, the library will wait for the element to appear (for 2s by default, I don't remember exactly), you don't need to use pause() function but when you use queryByTestId function, it run once time and not wait for the element, So everytime you do something that lead to a states changes, so you need to manually wait for it

3 Comments

This feels like a hack, it works for what I need (until I find a better solution). I have some components that fetch some data (through a hook), store that data in state without rendering anything, then when a button is clicked it sends that data somewhere else. I was having trouble ensuring that the mocked fetch would resolve before the fake button click, but adding this sleep worked for my tests.
To add to this solution, you may need to wrap the sleep in an act to avoid the Testing Library warning: await act(() => sleep(500));
@timgcarlson I updated the answer with further explanation
1

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); 
}

Comments

1

If someone ends up here looking for the solution for React Native:

expect(screen.queryByText("some text")).not.toBeOnTheScreen();

Comments

-1

don't want to bury the lead, so here's the right solution ✅

waitFor(() => queryByTestId(/car/) === null)

There are issues with all of the answers here so far...

don't use getByTestId, that'll have to wait 😴 for the timeout because it's expecting the element to eventually be there. Then it'll throw and you'll have to catch that, which is a less readable test. Finally you could have a RACE CONDITION 🚫 where getByTestId is evaluated before the element disappears and our test will flake.

Just using queryByTestId without waitFor is a problem if the page is changing at all and the element has not disappeared yet. RACE CONDITION 🚫

deleteCarButton.click();
expect(queryByTestId(/car/)).toBeNull(); //

if expect() gets evaluated before the click handler and render completes we'll have a bad time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.