Mid From PDF Node.js Node.js

How do you mock dependencies in Node.js tests?

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');
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();

});

});

More from Node.js Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details