Mid
From PDF
Node.js
Node.js
How do you mock dependencies in Node.js tests?
Short answer: Mocking replaces real dependencies with fake versions to isolate the unit you’re testing. Common tools: Sinon: For mocks, spies, and stubs. Proxyquire: Replace dependencies when requiring modules. Jest: Has built-in mocking capabilities. Example with Sinon: const sinon = require('sinon');
Example code
const myModule = require('../myModule');
const dependency = require('../dependency'); describe('test with mock', () => { it('should call dependency once', () => { const stub = sinon.stub(dependency, 'someMethod').returns(42);
const result = myModule.doSomething(); sinon.assert.calledOnce(stub); stub.restore(); }); });
Real-world example (ShopNest)
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png