简体   繁体   中英

How to test if <label> is not rendered in React.JS

I am trying to test if the component was rendered or not in my code depending on whether it was provided to the wrapping component or not. I am facing the issue of not being able to check if it or not because I can't think of a way to find it on the screen.

  return (
    <>
      <If condition={label?.length > 0}>
        <label htmlFor={name}>
          {label}
        </label>
      </If>

      <Field type="text" id={name} name={name} placeholder={placeholder} />
      <ErrorMessage name={name} component="small" />
    </>
  );

One (hack-ey) way of doing it was to provide the <label> with "aria-label" ( <label aria-label="customLabel"/> ), then using screen.findByLabelText("customLabel").not.toBeInTheDocument()

What can I use to find it without directly accessing the DOM elements?

In your case you need 2 things:

  1. await findBy* method to test that your element is rendered, and
  2. queryBy* method to test that your element is not rendered.

When your element is conditionally rendered you need to use findBy*, and you need to use await along with it ( expect(await findBy*(...)).toBeInTheDocument(); ).

Also, you need to mock your parent/wrapping component, and depending on that to make assertation.

From thedocs :

getBy...: Returns the matching node for a query, and throw a descriptive error if no elements match or if more than one match is found (use getAllBy instead if more than one element is expected).

queryBy...: Returns 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. Throws an error if more than one match is found (use queryAllBy instead if this is OK).

findBy...: Returns a Promise which resolves when an element is found which matches the given query. The promise is rejected if no element is found or if more than one element is found after a default timeout of 1000ms. If you need to find more than one element, use findAllBy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM