New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Node 18+: make nock
work native fetch
#2397
Comments
TBH neither of those directly mention Nock. Would it be possible to add I Think it might help prevent the need to mark things as duplicate. |
If upgrading
|
Do we have any updates to this? Would love to keep using nock but this is breaking our flow now. |
That's a good idea. Thoughts @mastermatt? If someone could get a pull request started that would be great. |
It should absolutely be documented in the Readme. |
For now we can recommend to set the For what it's worth, my net interceptor library (https://github.com/gr2m/node-net-interceptor) does intercept native fetch as it intercepts at the If anyone would like to dig into https://github.com/gr2m/node-net-interceptor and native Here is a starting point. Intercepting works, but I haven't digged into how the response needs to look like for it to successfully mock a full request lifecycle for the native import netInterceptor from "@gr2m/net-interceptor";
netInterceptor.start();
netInterceptor.on("connect", (socket, options, bypass) => {
console.log("intercepted!");
// bypass();
});
netInterceptor.on("connection", (socket) => {
socket.write(
`HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Accept-Ranges: bytes
Connection: keep-alive
works`
);
socket.end();
});
const response = await fetch("http://example.com");
console.log(await response.text()); Update: see working example below. |
fetch
functionnock
work native fetch
This could only help if one is not using native fetch by desire. Disabling native fetch just makes my code not working at all :) |
good point. I mostly work in projects where I know it's not ideal, but as a temporary workaround, could you for testing use node-fetch and make it the global |
The best solution I found so far is the import { SetupServer, setupServer } from 'msw/node';
import { rest } from 'msw';
import { myApiClient } from './my-api-client';
type ServerOptions = Parameters<typeof setupServer>;
const withRequestInterception =
(handlers: ServerOptions, test: (server: SetupServer) => any) => async () => {
const server = setupServer(...handlers);
server.listen();
return Promise.resolve(test(server)).finally(() => {
server.resetHandlers();
server.close();
});
};
describe('myApiClient', () => {
it(
'should work!',
withRequestInterception(
[
rest.get('https://my-mocked.url', (req, res, ctx) =>
res(ctx.status(200, 'Mocked status'))
),
],
async () => {
const response = await myApiClient('https://my-mocked.url');
expect(response.status).toEqual(200);
expect(response.statusText).toEqual('Mocked status');
}
)
);
}); |
Please state that nock does not work with fetch right at the top of your readme.md. Even the most basic nock example fails with the most common way of calling sites - fetch. I've wasted an hour before I realised this expected feature doesn't work: async function fetchExample() {
nock("http://example.com").get("/").reply(200, "Mocked response");
try {
const response = await fetch("http://example.com");
const data = await response.text();
console.log(data);
} catch (error) {
console.error("An error occurred during the fetch request:", error);
}
}
fetchExample(); |
I added a warning in dd15ba5 |
This comment was marked as duplicate.
This comment was marked as duplicate.
When testing the nock package does not know how to behave with the native fetch, so we use 'node-fetch' to make fetch testable with nock. More info: nock/nock#2397 (comment)
@gr2m, are there any plans to support this in near feature? Nock is a great testing library... |
I'm not able to work on it by myself right now, I just don't have the time. See my comment at #2397 (comment). I'd be happy to onboard a new co-maintainer if someone wants to take this on |
OK. Let me at least try... How can we do the onboarding? |
@mikicho works perfectly. Thanks very much! Now only recording support is missing to fully migrate |
Hello there, I'm trying this fetch beta feature for a couple of weeks now. |
@aannoune, fetch by itself doesn't support timeouts. If Nock ships an API that helps you mock a request timeout, then Nock has to provide that support explicitly by using an |
details here: nock/nock#2397
@kettanaito |
* fix(deps): update dependency probot to v13 * fix(app): use Probot logger properly * build(deps): tests need to use nock@14-beta details here: nock/nock#2397 --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Oscar Dominguez <[email protected]>
@Ugzuzg, the original question was about timeouts so that's what I assumed. You are right, for delaying responses you just have to take the mock delay into account, it's a different thing. |
@Ugzuzg : i confirm that my primary goal is to trigger a timeout error in fetch request to test the handling of a request falling into timeout. I there any AbortController support planned in Nock ? |
@aannoune Can you please share the code? (nock interceptor + fetch request) |
@mikicho i cannot share the full code of the fetch request (it is not my own code but another squad's lib i must use) but it is called with a regarding the interceptor : it is a rather simple one like |
This is great. I'd love to see fetch support added to recording as well. |
* refactor(http): use node-fetch instead of axios in http plugin Add also response header to result returned by salngroom that now is contains the fields: status, result, headers * refactor(http): use nock@beta in tests since latest stable nock does not support fetch nock/nock#2397
Hi @mikicho, thanks for adding support for native fetch! I haven't been able to pinpoint the actual problem yet on my side (I don't think this is a nock problem per se, so I didn't want to make an issue), but when trying to use nock in my jest tests, I get an error when nock tries to patch
The output of
Have you seen properties of I also wanted to add to this discussion since it's possible someone else has run into this/will run into this. |
@mkurapov Interesting. Is there something else that may override |
…k not intercepting calls to github with FAKE_CREDS solution: nock/nock#2397 (comment)
…ha (#63) * fix(deps): migrate to node.js 20 * fix: use node:test instead of mocha * fix: `SyntaxError: Cannot use import statement outside a module` on `make test` * fix(tests): `RequestError [HttpError]: Bad credentials` cause but nock not intercepting calls to github with FAKE_CREDS solution: nock/nock#2397 (comment) * fix(tests): make all tests run * $ npm i -D firebase-tools@latest * bump version to 1.7.1
Recording is well needed. Like when you nocking a 3rd party library and you don't even know which requests are happening, recording is the only way to go. Unfortunately at this moment on the project I'm working nock is just recording an empty array :( |
@mikicho it was a result of having an older version of jest. I was on jest 29.5.0, but upgrading to 29.7.0 fixes the problem. |
Please avoid duplicates
Context
Since node v18,
fetch
is now natively available and one does not require to installnode-fetch
or the like anymore. I have been using the native fetch quite successfully however I can't use it withnock
Alternatives
No response
If the feature request is accepted, would you be willing to submit a PR?
The text was updated successfully, but these errors were encountered: