- The analytics method window.track
- Stub the method after the visit
- Testing window.load call
- Stub every widow
- See also
The analytics method window.track
Imagine our app is loading a tiny analytics script that tracks the window load event.
1 | // example analytics lib |
The application can also track other events, for example creating and removing the todo items
1 | // adding a todo |
How do we test the analytics calls from the Cypress test?
Important: if you want the function to be stubbable, declare it as a property on the window object like
window.track = () => {...}orwindow.track = function () {...}. Do NOT simply declare a global function likefunction track () {...}, since the global function would simply clash with ourObject.definePropertyvariable with the same name. See the issue #15694 for example.
Stub the method after the visit
You can see me explaining how to stub the window.track after the page visit to track todo.add and todo.remove events in the video below
The final test code is below:
1 | /// <reference types="cypress" /> |
Testing window.load call
If we want to test that the window.load call happens, we have to stub the method window.track before the application calls it. We can use the cy.visit onBeforeLoad callback for this. It executes when the window object has been created, but the application code has not executed yet.
You can watch the video below
And see the finished code below
1 | /// <reference types="cypress" /> |
Stub every widow
If the browser navigates to a different page, or even simply reloads the current page, the window object is recreated, removing our stub. Thus we need to recreate the stub every time a new window object is created and before the application code is loaded. We can do this by using the cy.on event callback:
The finished code is below:
1 | it('tracks page load', () => { |
See also
- Stub window.open blog post
- Guide Stubs, Spies, and Clocks