question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Intercept resets compatible content type when body is an object

See original GitHub issue

Current behavior

The following test passes:

const axios = require('axios');

it('overwrites the content-type header', () => {
    cy.intercept('http://localhost:3000', (req) => {
        req.on('response', (res) => {
            res.send({
                statusCode: 500,
                headers: {
                    // A variant of the normal json content type specifically designed
                    // for error messages.
                    'content-type': 'application/problem+json',
                    'access-control-allow-origin': '*',
                },
                body: {
                    status: 500,
                    title: 'Internal Server Error',
                },
            });
        });
    });

    axios
        .get('http://localhost:3000')
        .catch((error) => {
            // Note that this asserts the standard json content type
            expect(error.response.headers['content-type']).to.equal('application/json');
        });
});

image

Desired behavior

.intercept() should not overwrite the content type if I explicitly provide one. Especially if my content type matches the response body.

Or, in other words. The following test should pass:

The test
const axios = require('axios');

it('does not overwrite the content-type header', () => {
  cy.intercept('http://localhost:3000', (req) => {
      req.on('response', (res) => {
          res.send({
              statusCode: 500,
              headers: {
                  'content-type': 'application/problem+json',
                  'access-control-allow-origin': '*',
              },
              body: {
                  status: 500,
                  title: 'Internal Server Error',
              },
          });
      });
  });

  axios
      .get('http://localhost:3000')
      .catch((error) => {
          // Now asserts the content type for Problem JSON
          expect(error.response.headers['content-type']).to.equal('application/problem+json');
      });
});

Test code to reproduce

As above 😃

I also have a random server up at http://localhost:3000. Since we’re replacing the response of the server anyway, it really doesn’t matter what’s running there. My server is an Express Hello World 😃

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

Versions

Cypress: 7.5.0

Workaround

I already found a workaround. I’ll share it in case it helps someone else.

This only happens when your response body is an object, so all you have to do is stringify it like so:

const axios = require('axios');

it('overwrites the content-type header', () => {
    cy.intercept('http://localhost:3000', (req) => {
        req.on('response', (res) => {
            res.send({
                statusCode: 500,
                headers: {
                    'content-type': 'application/problem+json',
                    'access-control-allow-origin': '*',
                },
                // Stringify as a workaround. This issue only happens when body is an
                // object. `JSON.stringify` turns it into a string instead.
                body: JSON.stringify({
                    status: 500,
                    title: 'Internal Server Error',
                }),
            });
        });
    });

    axios
        .get('http://localhost:3000')
        .catch((error) => {
            expect(error.response.headers['content-type']).to.equal('application/problem+json');
        });
});

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
cypress-bot[bot]commented, Jul 12, 2021

The code for this is done in cypress-io/cypress#17199, but has yet to be released. We’ll update this issue and reference the changelog when it’s released.

0reactions
cypress-bot[bot]commented, Aug 16, 2021

Released in 8.3.0.

This comment thread has been locked. If you are still experiencing this issue after upgrading to Cypress v8.3.0, please open a new issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

intercept - Cypress Documentation
routeMatcher is an object used to match the incoming HTTP requests with this intercepted ... If a JSON Content-Type was used and the...
Read more >
Who sets response content-type in Spring MVC ...
I found solution for Spring 3.1. with using @ResponseBody annotation. Here is example of controller using Json output: @RequestMapping(value = "/getDealers" ...
Read more >
Intercept HTTP requests - Mozilla - MDN Web Docs
To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request....
Read more >
Cypress cy.intercept Problems - Gleb Bahmutov
We might write a test like this to spy on this call: ... Let's inspect the interception object yielded by the cy.wait command....
Read more >
Intercept Service - WebdriverIO
Returns array of request objects. browser.hasPendingRequests()​. A utility method that checks whether any HTTP requests are still pending. Can be used by tests ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found