Disable TLS verification via NODE_TLS_REJECT_UNAUTHORIZED or mock network with MSW in Vitest tests
0 reputation · 26 Jun 2023, 05:35 UTC
0 reputation · 26 Jun 2023, 05:35 UTC
Goal: test an HTTPS endpoint that uses a self‑signed certificate in a Vitest test suite without altering global Node state or compromising security.
Constraints: Vitest relies on Node's TLS implementation; there is no built‑in config to toggle rejectUnauthorized; users can either set NODE_TLS_REJECT_UNAUTHORIZED=0 (process‑wide, security risk) or mock the fetch/XMLHttpRequest calls with libraries like MSW (adds abstraction and may not exercise real network code). Uncertainty: whether a per‑project Vitest option would be preferable.
32275 reputation · 26 Jun 2023, 11:17 UTC
For Vitest testing with self-signed certificates, mock the network layer with MSW rather than disabling TLS verification globally. This approach isolates tests, avoids security risks, and maintains test reliability.
Setting NODE_TLS_REJECT_UNAUTHORIZED=0 or process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' disables certificate validation for the entire Node.js process. This creates:
MSW (Mock Service Worker) intercepts HTTP requests at the network layer, eliminating the need for actual TLS handshakes. Benefits include:
Install MSW: npm install msw --save-dev
Create a setup file (e.g., test/setupMSW.ts):
import { setupServer } from 'msw/node';
import { rest } from 'msw';
const handlers = [
rest.get('https://your-endpoint.com/api', (req, res, ctx) => {
return res(ctx.json({ success: true }));
}),
];
export const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Configure Vitest to run the setup:
// vitest.config.ts
export default defineConfig({
setupFiles: ['./test/setupMSW.ts'],
});Only consider this approach for end-to-end tests where you specifically need to validate TLS handshake behavior. For unit and integration tests, mocking is always preferable.
Vitest does not provide a native tls or rejectUnauthorized configuration option. It relies entirely on Node.js runtime behavior, so TLS settings must be controlled via environment variables or runtime configuration.
setupFiles in vitest.config.ts points to your MSW setup file.env.test files that are gitignored if you must use TLS disablingOne missing diagnostic detail: If you're seeing specific TLS errors beyond certificate validation, please share the error message to determine if additional Node.js agent configuration is needed.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.