mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.94k stars 518 forks source link

`[ERR_INVALID_URL]: Invalid URL: [object Object]` on object based passthrough requests #749

Closed esamattis closed 3 years ago

esamattis commented 3 years ago

Environment

Name Version
msw 0.28.2
node v12.18.4
OS macOS Mojave

When doing a http request with the node.js http client with an object like:

{
    hostname: "localhost",
    path: "/",
    origin: "http://localhost:3728",
    port: 3728,
    method: "GET",
}

the error in the subject is thrown.

For some reason it does not like the origin key. If it is removed the this works as expected.

So fix is easy in in userland. In theory. Unfortunately I'm using @elastic/elasticsearch which is creating requests like this internally in some situations and I have no control over it.

Here's a jest test reproducing the error

import http from "http";
import { setupServer } from "msw/node";

test("can make raw passthrough request with an object", async () => {
    const mockServer = setupServer(); // No interceptors!
    mockServer.listen();

    // Real server handling the pass through
    const server = http.createServer((req, res) => {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end("Hello from real server");
    });

    await new Promise<void>((resolve) => {
        server.listen(3728, () => {
            resolve();
        });
    });

    const doGet = async () => {
        return await new Promise<http.IncomingMessage>((resolve, reject) => {
            http.request(
                {
                    hostname: "localhost",
                    path: "/",
                    origin: "http://localhost:3728",
                    port: 3728,
                    method: "GET",
                },
                resolve,
            )
                .on("error", reject)
                .end();
        });
    };

    let res;

    try {
        res = await doGet();
    } finally {
        server.close();
    }

    expect(res.statusCode).toEqual(200);
});

This crashes with

TypeError: Invalid URL: [object Object]TypeError [ERR_INVALID_URL]: Invalid URL: [object Object]

From debugging the source via node_modules the error seems to origin from the request.url.toString() call here:

https://github.com/mswjs/msw/blob/1562bfc901c930bffc8c5eb150bb855b54020676/src/utils/request/setRequestCookies.ts#L10

Some screenshots from a vscode debug session:

node_modules/msw/node/lib/index.js

image

image

esamattis commented 3 years ago

Ok, sorry, this is duplicate of #705 and is fixed in https://github.com/mswjs/interceptors/commit/692433e62c2110d59a5e6940f3a0d26eb2c8d0a0

I just had old version of msw depending on old interceptors package.