msw: Unable to be used alongside superagent

Describe the bug

I have an express server that makes calls to third party apis, and I would like to test my express server using supertest and mock the third party api requests using msw.

When starting the msw node server, all supertest requests fail with the following error:

TypeError [ERR_INVALID_URL]: Invalid URL: undefined//undefined
      at onParseError (internal/url.js:241:17)
      at new URL (internal/url.js:319:5)
      at new URL (internal/url.js:316:22)
      at normalizeHttpRequestParams (node_modules/node-request-interceptor/lib/http/ClientRequest/normalizeHttpRequestParams.js:29:57)
      at new ClientRequestOverride (node_modules/node-request-interceptor/lib/http/ClientRequest/ClientRequestOverride.js:65:74)
      at handleRequest (node_modules/node-request-interceptor/lib/http/override.js:28:12)
      at Object.requestOverride [as request] (node_modules/node-request-interceptor/lib/http/override.js:55:20)
      at Test.Request.request (node_modules/superagent/lib/node/index.js:622:31)
      at Test.Request.end (node_modules/superagent/lib/node/index.js:764:8)
      at Test.end (node_modules/supertest/lib/test.js:125:7)

Environment

  • msw: 0.19.0
  • nodejs: 10.16.3
  • npm: 6.9.0

To Reproduce

Steps to reproduce the behavior:

import express from 'express';
import request from 'supertest';
import { setupServer } from 'msw/node';

const app = express();
app.get('/', (req, res) => res.send('hello world'));

setupServer().listen();

request(app)
  .get('/')
  .then((res) => {
    console.log(res);
  });

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 3
  • Comments: 16 (9 by maintainers)

Most upvoted comments

Technical details

The issue is caused by the RequestOptions object supertest creates. Unlike regular NodeJS RequestOptions, the one from the mentioned library doesn’t have the protocol and hostname property, which resulted into the derived url being undefined//undefined.

I’m going to provide a fix in the node-request-interceptor library (responsible for requests interception and mocking in Node) and propagate it to MSW.

Here is the reproduction repo: https://github.com/bopfer/msw-supertest-issues

I tried to make it as slim as possible to show the issue.

The post is to my GraphQL app via supertest, which I do not want mocked. In there, the resolver code does a get to the 3rd party API. That’s the part I would like mocked.