I was trying to log the API response time in Cypress, but could not find any solution. What to use, cy.intercept()
or cy.request()
?
I was trying to use the advice like this:
cy.intercept('POST', '**/create-insurance-view-model', (req) => {
const start = Date.now()
req.continue(res => {
res.responseTime = Date.now() - start;
})
}).as('apiViewModel')
cy.wait('@apiViewModel').then(intercept => {
cy.log(`Time to get the license plate data was: ${intercept.response.responseTime} seconds`)
})
And I am getting undefined in the log.
Ok, so I solved it like this, thanks to the help from Paolo. Addes custom commands.
let responseTime
Cypress.Commands.add('inteceptasd', (method, request, apiVariable) => {
cy.intercept(method, request, (req) => {
const start = Date.now()
req.reply(() => {
responseTime = (Date.now() - start) / 1000
})
}).as(apiVariable)
})
Cypress.Commands.add('waitasd', (apiVariable, timeVariable, describe) => {
cy.wait(apiVariable).then(() => {
timeVariable = responseTime
cy.log(timeVariable)
cy.on('test:after:run', (test) => addContext({ test }, `Time to get the endpoint data ${apiVariable} was: ${timeVariable}s - ${describe}`))
})
})
Then I used it in test like this
cy.interceptForResponseTime('GET', '**/get-vehicle-identification*', 'apiVehicleByVin')
cy.get('cebia-price-loader > div > .btn').contains(domData.btnLoadPrice).should('exist').click()
cy.waitWithResponseTime('@apiVehicleByVin', 'timeVehicleByVin', 'description for this api time check')