gpt4 book ai didi

javascript - Cypress - 在页面导航之前测试点击事件

转载 作者:行者123 更新时间:2023-12-02 23:03:50 25 4
gpt4 key购买 nike

我正在尝试测试我的 google tag manager 'productClick' event正在点击之后但页面导航之前进行注册。这是我所拥有的:

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 模式下通过。其他测试正在测试与 Google 标签管理器无关的内容,但窗口中发生了 GTM push 调用。这几乎就像 cy.spy 在我告诉它之前就开始进行 spy 事件。

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

最佳答案

想通了。我仍然不确定为什么其他推送调用最终出现在 spy 对象中,但我可能无法控制它。因此,与其监听一个调用,不如找到与此事件相关的调用并对其进行断言。还需要使用 cy.get 来调用 spy 。答案在this帖子对我有帮助。

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;
});

});
});
});
});

});

关于javascript - Cypress - 在页面导航之前测试点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57679415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com