diff --git a/packages/driver/cypress/integration/commands/misc_spec.js b/packages/driver/cypress/integration/commands/misc_spec.js index ba5018530a7c..4e517851d87a 100644 --- a/packages/driver/cypress/integration/commands/misc_spec.js +++ b/packages/driver/cypress/integration/commands/misc_spec.js @@ -72,6 +72,18 @@ describe('src/cy/commands/misc', () => { }) }) }) + + // https://github.com/cypress-io/cypress/issues/8084 + it('log does not corrupt the stack and returns subject correctly', () => { + cy.wrap({ a: 42 }).then(async (data) => { + cy.log('count', Object.keys(data).length) + cy.log('another log') + + return await Object.keys(data).length + }).then((test) => { + expect(test).to.eq(1) + }) + }) }) }) diff --git a/packages/driver/src/cy/commands/misc.js b/packages/driver/src/cy/commands/misc.js index 40ad31aa7b18..7e0783ae46d6 100644 --- a/packages/driver/src/cy/commands/misc.js +++ b/packages/driver/src/cy/commands/misc.js @@ -4,7 +4,7 @@ const Promise = require('bluebird') const $dom = require('../../dom') const $errUtils = require('../../cypress/error_utils') -module.exports = (Commands, Cypress, cy) => { +module.exports = (Commands, Cypress, cy, state) => { Commands.addAll({ prevSubject: 'optional' }, { end () { return null @@ -17,6 +17,22 @@ module.exports = (Commands, Cypress, cy) => { }, log (msg, args) { + // https://github.com/cypress-io/cypress/issues/8084 + // The return value of cy.log() corrupts the command stack, so cy.then() returned the wrong value + // when cy.log() is used inside it. + // The code below restore the stack when cy.log() is injected in cy.then(). + if (state('current').get('injected')) { + const restoreCmdIndex = state('index') + 1 + + cy.queue.splice(restoreCmdIndex, 0, { + args: [state('subject')], + name: 'log-restore', + fn: (subject) => subject, + }) + + state('index', restoreCmdIndex) + } + Cypress.log({ end: true, snapshot: true, diff --git a/packages/driver/src/cypress/cy.js b/packages/driver/src/cypress/cy.js index cfcc7b3fdffe..b4252730c879 100644 --- a/packages/driver/src/cypress/cy.js +++ b/packages/driver/src/cypress/cy.js @@ -1099,8 +1099,9 @@ const create = function (specWindow, Cypress, Cookies, state, config, log) { // dont enqueue / inject any new commands if // onInjectCommand returns false const onInjectCommand = state('onInjectCommand') + const injected = _.isFunction(onInjectCommand) - if (_.isFunction(onInjectCommand)) { + if (injected) { if (onInjectCommand.call(cy, name, ...args) === false) { return } @@ -1112,6 +1113,7 @@ const create = function (specWindow, Cypress, Cookies, state, config, log) { type, chainerId, userInvocationStack, + injected, fn: wrap(firstCall), })