Nock@14 breaks ClientRequest.setTimeout
Please avoid duplicates
- I checked all open bugs and none of them matched my problem.
Reproducible test case
https://github.com/TrevorKarjanis/nock-bug-2919
Nock Version
14.0.10
Node Version
24.8.0 and 20.19.5
TypeScript Version
N/A
What happened?
The Node.js native API ClientRequest.setTimeout does not function with [email protected]. Requests fail to timeout. This also breaks Axios with certain configurations and is a duplicate of closed bug #2860 which is specific to Axios.
Additionally, examples/socket-delay-abort.js is out-of-date. It uses deprecated APIs.
Reproduction
RunKit does not work. The following GitHub repository is provided instead. See the section Test Native Node.js APIs with Nock and nock-native-timeout.test.js. This code is provided below for completeness.
https://github.com/TrevorKarjanis/nock-bug-2919
The reproduction repository also provides tests for Axios and native Node.js APIs without nock.
Axios
Reproduction Code
TrevorKarjanis/nock-bug-2919/blob/main/nock-native-timeout.test.js
import http from 'http';
import nock from 'nock';
main();
async function main() {
let listener;
try {
const delay = 1000;
const url = 'http://localhost:81';
nock(url).get('/').delay(delay).reply(200);
let failures = 0;
let success = await request(url, delay, true);
if (!success) failures += 1;
nock(url).get('/').delay(delay).reply(200);
success = await request(url, delay, false);
if (!success) failures += 1;
if (failures) console.log(`\n${failures} tests failed`);
else console.log('\nAll tests passed');
} finally {
listener?.close();
}
}
async function request(url, delay, option = true) {
return new Promise(resolve => {
const ms = delay / 2;
const timeout = option ? ms : undefined;
const request = http.request(url, { timeout }, response => {
console.log(`Response received with status code ${response.statusCode}`);
console.log('Request failed to timeout');
});
if (timeout) {
console.log('Testing timeout set with http.request option');
} else {
console.log('\nTesting timeout with ClientRequest.setTimeout');
request.setTimeout(ms);
}
let succeeded = false;
request.on('close', () => resolve(succeeded));
request.on('error', e => console.error(e.message));
request.on('timeout', () => {
succeeded = true;
request.destroy(new Error('Request timed out successfully'));
});
console.log(`Sending request to ${url}`);
request.end();
});
}Would you be interested in contributing a fix?
- yes
Source: nock/nock