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