nock / nock

HTTP server mocking and expectations library for Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nock fails to intercept http(s) requests from an ESM library

ClementValot opened this issue · comments

Please avoid duplicates

Reproducible test case

https://github.com/ClementValot/stripe-regression

Nock Version

13.3.0

Node Version

16.15.1

TypeScript Version

No response

What happened?

Please find a code snippet there

I identified the issue when upgrading stripe-node from a version prior to 11.14.0 to a version newer than 11.15.0.
Prior to that I could mock the Stripe SDK requests with Nock, now the requests aren't detected and intercepted.

The Node SDK uses http and https node built-ins, the change that occurred in 11.15.0 was introducing two exports, one cjs and one esm lib.

Would you be interested in contributing a fix?

  • yes

This is caused by the fact that the Stripe lib is essentially caching the native http and https module on import of NodeHttpClient, unfortunately, this means that Nock is not able to monkey patch the modules after this point.

You can get the provided tests to pass by ensuring that Nock gets required/imported first.

I know this isn't a great response, but the reality is, unless Nock gets a major rewrite, this isn't going to be fixed. The monkey patching of native modules is fundamental to Nock's design (which dates back to 2011, Node v0.4).

I kinda fail to understand why the same code would work before the Stripe rewrite into ESM. Is this due to a difference in how node resolves import/require with cjs vs ESM?

It has to do with their code no longer holding onto a reference to the actual exported object from the native module and instead holding a new object with all the possible imports from the module attached to it. Which means they no longer reference the object that Nock is monkey patching.

As you indicated, changing the order of the imports "magically" fixed it :)

I don't see this easy trick mentioned anywhere in the README, maybe it should?

FWIW we just changed stripe-node to play more nicely with monkey-patching by switching to the default import syntax. Figured I'd leave a note in case another library maintainer finds this issue and wanted some prior art.

That's nice of you!
I'll test that ASAP :)