I'm trying to test if the correct data is being tracked by GA4. However, I have the problem that an article can have several prices depending on whether it is played on the integration environment or on the production environment.
The getCorrectPrice command:
Cypress.Commands.add('getCorrectPrice', () => {
cy.url().then(url => {
const currentURL = url.split('/de/');
const pathURL = currentURL[0];
if(pathURL === environment.production)
{
return productData.product.trackedPrice.production
} else {
return productData.product.trackedPrice.integration
}
})
})
The Test:
it.only('should track add to cart on product detail page', function() {
//data
const expectedAddToCartEvent = {
event: 'add_to_cart',
ecommerce: {
items: [
{
item_id: '000000',
item_name: 'product',
currency: 'EUR',
item_brand: 'goodbrand',
item_category: 'some Category',
item_category2: 'some Category 2',
price: cy.getCorrectPrice().then((price) => {
return price
}),
quantity: 1,
},
],
},
}
//arrange
cy.visitWithBasicAuth(routes.productDetail)
//act
cy.get(selectors.resultList.addToCartButton).eq(1).click({ force: true })
//assert
cy.wait('@addProduct').then(() => {
cy.getSpecificEventFromDataLayer('add_to_cart').then(
(actualAddToCartEvent) => {
cy.wrap(actualAddToCartEvent, { timeout: 0}).should(
spok(expectedAddToCartEvent),
)
}
)
})
})
My problem is that if I display the price in the console in the expectedAddToCartEvent, I get the correct price. However, when the test runs, the following error message appears:
I've already tried to work with cy.wait and .then but it doesn't work
The problem is cy.getCorrectPrice()
returns a Chainable
value which you cannot assign to the price property.
Try this structure instead
it('should track add to cart on product detail page', function() {
cy.getCorrectPrice().then(correctPrice => {
const expectedAddToCartEvent = {
event: 'add_to_cart',
ecommerce: {
items: [
{
item_id: '000000',
item_name: 'product',
currency: 'EUR',
item_brand: 'goodbrand',
item_category: 'some Category',
item_category2: 'some Category 2',
price: correctPrice,
quantity: 1,
},
],
},
}
//arrange
cy.visitWithBasicAuth(routes.productDetail)
//act
cy.get(selectors.resultList.addToCartButton).eq(1).click({ force: true })
//assert
cy.wait('@addProduct').then(() => {
cy.getSpecificEventFromDataLayer('add_to_cart')
.then((actualAddToCartEvent) => {
cy.wrap(actualAddToCartEvent, { timeout: 0})
.should(spok(expectedAddToCartEvent))
})
})
})
})