I want to use MutationObserver
with Cypress because it feels like an appropriate mechanism to use for detecting specific changes occurred to the DOM and then interact with element(s) that were added.
Assume that I have a UI that has 3 buttons and a div.new-elements-wrapper
. Clicking each button results in a new div
element into div.new-elements-wrapper
with a data-type
attribute of value button-a
, button-b
, and button-c
for buttons A, B, and C, respectively. It's possible that these elements can be randomly inserted, not just appended to the end of the div.new-elements-wrapper
container.
I want to write a test that effectively is:
- Click button A.
- Wait for new element to be added to
div.new-elements-wrapper
region. - When new element appears in region, validate that it has a
data-type
attribute and that it's value isbutton-a
.
Repeat for buttons B, and C.
For step 2, I don't want to continue on until a MutationObserver
, configured to look specifically at div.new-elements-wrapper
, has a single node in a mutation's nodesAddedList
. Then, in step 3, validate the data-type
attribute is button-a
.
For the Cypress wizards out there, how would you do this?
EDIT: Note that there is no uniquely identifying information available on these components that are added. If there are two elements, both button-a
, then the only way to know which was added would be to informed by a MutationObserver
.