赛普拉斯 - 在页面导航之前测试点击事件



我正在尝试测试我的谷歌跟踪代码管理器"productClick"事件是否在点击但在页面导航之前注册。这是我所拥有的:

describe("Test Product Listing Page", () => {
beforeEach(function() {
cy.visit("/productlisting");
});
...(other tests)...
it("Test GTM productClick", function() {
cy.window().then(win => {
// listen to GTM's dataLayer.push method
const dlp = cy.spy(win.dataLayer, "push");
// extract SKUID from first product on the page
cy.get('[data-js="productlisting"] [data-product-skuid]')
.first() 
.invoke("attr", "data-product-skuid")
.then(skuid => {
// click on the first link in the item's container
cy.get(`[data-product-skuid="${skuid}"] a`)
.first()
.click()
.then(() => {
// passes in interactive mode but not CI mode!
expect(dlp).to.be.calledOnce;
// test that argument passed is the item clicked
expect(dlp.args[0][0].ecommerce.click.products[0].id).to.equal(skuid);
// test that GTM returns true
expect(dlp.returnValues[0]).to.be.true;
});
});
});
});
}); 

cy.spy((似乎是我需要的,事实上它在交互模式下效果很好。 但在 CI 模式下,它失败并显示:

AssertionError: expected push to have been called exactly once, but it was called twice
The following calls were made:
push(Object{3}) => true at Array.proxy [as push] (https://my.site.com/__cypress/runner/cypress_runner.js:62335:22)
push(Object{4}) => true at Array.proxy [as push] (https://my.site.com/__cypress/runner/cypress_runner.js:62335:22)

但前提是规范上有其他测试!如果我将测试更改为it.only它会在 CI 模式下通过。 其他测试正在测试与谷歌标签管理器无关的内容,但窗口中发生了GTMpush调用。 这几乎就像cy.spy在我告诉它之前就开始间谍活动一样。

我很困惑。 我在这里错过了什么吗? 有没有更好的方法来测试点击后预导航?

想通了。 我仍然不确定为什么其他推送调用最终出现在间谍对象中,但我可能无法控制它。 因此,与其监听一个呼叫,不如找到与此事件相关的呼叫并断言反对该呼叫。 还需要用cy.get打电话给间谍。这篇文章中的答案帮助了我。

describe("Test Product Listing Page", () => {
beforeEach(function() {
cy.visit("/productlisting");
});
...(other tests)...
it("Test GTM productClick", function() {
cy.window().then(win => {
// listen to GTM's dataLayer.push method
cy.spy(win.dataLayer, "push").as("dlp");
// extract SKUID from first product on the page
cy.get('[data-js="productlisting"] [data-product-skuid]')
.first() 
.invoke("attr", "data-product-skuid")
.then(skuid => {
// click on the first link in the item's container
cy.get(`[data-product-skuid="${skuid}"] a`)
.first()
.click()
.then(() => {
// use cy.get for retry-ability
cy.get("@dlp").should(dlp => {
// find the index of the argument that corresponds to this event
const idx = dlp.args.findIndex(i => i[0].event === "productClick");
// then you can run assertions
expect(dlp.args[idx][0].ecommerce.add.products[0].id).to.equal(skuid);
expect(dlp.returnValues[idx]).to.be.true;
});
});
});
});
});
}); 

最新更新