Tengo un div con el siguiente html
<div data-cy="pop" style="margin-right:5px;">12,300</div> Estoy tratando de obtener 12,3001 , convertirlo en un int y guardar el valor para usarlo en otra función. Estoy recibiendo este error.
cy.then() failed because you are mixing up async and sync code.The value you synchronously returned was: 12300
Aquí está mi código para obtener el valor.
cy.elem('pop').invoke('text').then((num) => { const res = parseInt(num.replaceAll(',','')) return res })¿Alguien sabe lo que estoy haciendo mal?
No está claro cómo está intentando pasar el valor de su int analizado a otra función.
Una forma de guardar el valor de algo es con un alias . Para hacer eso, necesitará usar .as() .
cy.elem('pop') .invoke('text') .then((num) => { return parseInt(num.replaceAll(',','')) }) .as('num') // later down in your code cy.get('@num') .then(number => { functionYouWantToPassYourNumber(number) })Bit of a edge-case, TLDR: return cy.wrap(res) .
Si ejecuto esto como una prueba mínima para su código, pasa
const num = "12,300"; cy.wrap(num).then((numAsString) => { const numAsInt = parseInt(numAsString.replace(",", "")); return numAsInt }) .then(num => { cy.log(num) // logs 12300 ✅ }) Si agrego una línea asíncrona cy.wait(5000) (por ejemplo), falla
const num = "12,300"; cy.wrap(num).then((numAsString) => { const numAsInt = parseInt(numAsString.replace(",", "")); cy.wait(5000) return numAsInt }) .then(num => { cy.log(num) ❌ }) Si luego cy.wrap() el resultado, pasa de nuevo
const num = "12,300"; cy.wrap(num).then((numAsString) => { const numAsInt = parseInt(numAsString.replace(",", "")); cy.wait(5000) return cy.wrap(numAsInt) }) .then(num => { cy.log(num) // logs 12300 ✅ }) Teóricamente, su código debería pasar, pero si tiene otro comando dentro de .then() , podría estar causándolo.
O es posible cy.elem('pop') lo esté causando.
Como referencia, esta es la propia prueba de Cypress para el error.
describe("errors", {defaultCommandTimeout: 100}, () => { beforeEach(function () { this.logs = []; cy.on("log:added", (attrs, log) => { this.lastLog = log; this.logs?.push(log); }); return null; }); it("throws when mixing up async + sync return values", function (done) { cy.on("fail", (err) => { const { lastLog } = this; assertLogLength(this.logs, 1) expect(lastLog.get("error")).to.eq(err); expect(err.message).to.include( "`cy.then()` failed because you are mixing up async and sync code." ); done(); }); cy.then(() => { cy.wait(5000); return "foo"; }); }); });