I'm trying to test a React component that conditionally renders null using Cypress component testing. Here's a simplified version of my component:
const MyComponent = () => {
if (someCondition) {
return null;
}
return (
<div>
{/* UI content */}
</div>
);
};
I want to write a test that checks if the component renders nothing when the condition is true. Here's what I have so far:
it("should render nothing if condition is true", () => {
cy.pageMount(<MyComponent />);
// How can I assert that the component rendered null?
});
I'm not sure how to assert that the component actually rendered null. Is there a way to check for the absence of the component in the DOM using Cypress?
I've tried looking for documentation on testing null renders with Cypress, but haven't found a clear solution. Any help or guidance would be greatly appreciated!
Note: I'm using Cypress component testing, not end-to-end testing.
In the absence of something to identify the component, you can check the inner HTML of the element <div data-cy-root>
which Cypress adds to the DOM as a mounting point.
Obviously, the component is (almost?) never actually totally devoid of distinguishing features, you could use any of the text or attribute selection methods Cypress provides, then simply assert it does not exist.
But let's say it's a code-only component such as a data-context provider, purely there to pass state to React, so there is nothing to select it by except it's top-level <div>
tag.
For example, if I set up the provided example component so that it doesn't mount
import React from 'react'
const someCondition = true
export const MyComponent = () => {
if (someCondition) {
return null;
}
return (
<div>
I'm mounting now
</div>
);
}
I can test it with
import React from 'react'
import {MyComponent} from './MyComponent.js'
console.clear()
it("should render nothing if condition is true", () => {
cy.mount(<MyComponent data-test-id='my-component' />)
cy.get('div[data-cy-root]')
.find('div')
.should('not.exist')
})
and the test passes.
To make sure I'm not spoofing myself, I flip someCondition
to false
and the test now fails.