In the bahmutov/sorted-table-example example, the application sets and removes DOM element attributes:
1 | function enableButtons() { |
The application updates the table body by assigning the .innerHTML
property
1 | function sortTable() { |
Can we a) detect when the application is calling the .removeAttribute('disabled')
method on a specific DOM element and b) spy on the .innerHTML
property assignment?
Spy on removeAttribute
From our spec, first we need to access the DOM element, which we can do using $button[0]
index. Then we use the standard cy.spy to create a spy around the button's removeAttribute
method.
1 | beforeEach(() => { |
It is almost too easy.
Spy on innerHTML property assignment
Spying / stubbing methods is easy, what about spying on the element's innerHTML = ...
assignment? It is a little trickier, as we need to find the actual native DOM implementation via Object.getOwnPropertyDescriptor
to call it from the spy. Browser DOM elements have a hierarchy of classes, and we need to travel up the prototype chain to find the implementation we can call ourselves. Here is my finding the property innerHTML
using the $0
table body element as a start.
Luckily we can abstract finding any property descriptor into a utility function findPropertyDescriptor
and then we put our test innerHTML descriptor with setter and getter onto the DOM element. Our implementation calls a sinon stub we construct with cy.stub command.
1 | beforeEach(() => { |
Almost too easy.
📚 For more stub and spies examples, see my Spies, Stubs & Clocks page and this Cypress Guide.