'Cypress - How can I check Google Events fired before the new page loads
This is the scenario:
- User accesses
index.com
- Clicks the X button
- A Google Analytic event is fired here <-- I want to check this event
- User is redirected to a new page <-- Events are not longer here
This is my code:
describe("Desktop - Listing details - Google Analytics", () => {
slugs.forEach((slug, index) => {
context(`For ${slugs[index]}`, () => {
beforeEach(() => {
const ga = cy.stub().as("ga");
cy.on("window:before:load", win => {
Object.defineProperty(win, "ga", {
configurable: false,
get: () => ga, // always return the stub
set: () => {} // don't allow actual google analytics to overwrite this property
});
});
cy.visit(`/url/a/${slug}/`);
});
context("Navigation tab", () => {
it("Pricing tab", function() {
cy.get(`[class="nav-links"] > li`)
.eq(1)
.click(); // Here a new page loads and the events are not longer present
cy.get("@ga").should(`be.calledWith`, `send`, {
hitType: "event",
eventCategory: "navigation-bar",
eventAction: "go-to_product_pricing",
eventLabel: "navigation-tab"
});
});
});
});
});
});
And a second attempt:
Cypress.on('window:before:load', (win) => {
// because this is called before any scripts
// have loaded - the ga function is undefined
// so we need to create it.
win.ga = cy.stub().as('ga')
})
describe("Desktop - Listing details - Google Analytics", () => {
slugs.forEach((slug, index) => {
context(`For ${slugs[index]}`, () => {
beforeEach(() => {
cy.visit(`/url/a/${slug}/`);
});
context("Navigation tab", () => {
it("Pricing tab", function() {
cy.get(`[class="nav-links"] > li`)
.eq(1)
.click(); // Here a new page loads and the events are not longer present
cy.get("@ga").should(`be.calledWith`, `send`, {
hitType: "event",
eventCategory: "navigation-bar",
eventAction: "go-to_product_pricing",
eventLabel: "navigation-tab"
});
});
});
});
});
});
The thing is that Cypress is making the assertion in the New page, and the events I want to check are not longer there.
How can I test this? Honestly, I tried everything.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|