From 6b851e9257c54245e9e733d5dc1cc7256e6a8813 Mon Sep 17 00:00:00 2001 From: Chris Breiding Date: Tue, 9 Nov 2021 15:04:25 -0500 Subject: [PATCH] fix: bind this correctly when setting response headers with cy.route() --- .../cypress/integration/commands/xhr_spec.js | 27 +++++++++++++++++++ packages/driver/src/cypress/server.ts | 3 +-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/driver/cypress/integration/commands/xhr_spec.js b/packages/driver/cypress/integration/commands/xhr_spec.js index 8f0061d6c1b8..2c785e73dd80 100644 --- a/packages/driver/cypress/integration/commands/xhr_spec.js +++ b/packages/driver/cypress/integration/commands/xhr_spec.js @@ -1659,6 +1659,33 @@ describe('src/cy/commands/xhr', () => { }) }) + // https://github.com/cypress-io/cypress/issues/18858 + it('can stub headers', (done) => { + cy + .route({ + url: '/foo', + response: '', + headers: { + 'some-header': 'header-value', + }, + }).as('getFoo') + .window().then((win) => { + win.$.ajax({ + url: '/foo', + error (_a, _b, err) { + done(`Errored but should not have: ${err.stack}`) + }, + }) + + return null + }) + .wait('@getFoo') + .then((xhr) => { + expect(xhr.response.headers['some-header']).to.equal('header-value') + done() + }) + }) + // https://github.com/cypress-io/cypress/issues/2372 it('warns if a percent-encoded URL is used', () => { cy.spy(Cypress.utils, 'warning') diff --git a/packages/driver/src/cypress/server.ts b/packages/driver/src/cypress/server.ts index 16ed777a71a0..e039d1d55b7f 100644 --- a/packages/driver/src/cypress/server.ts +++ b/packages/driver/src/cypress/server.ts @@ -200,8 +200,7 @@ export class Server { this.setHeader(xhr, 'response', route.response, responser) this.setHeader(xhr, 'matched', `${route.url}`) this.setHeader(xhr, 'delay', route.delay) - - return this.setHeader(xhr, 'headers', route.headers, this.transformHeaders) + this.setHeader(xhr, 'headers', route.headers, this.transformHeaders.bind(this)) } route (attrs = {}) {