Dependency injection

The idea of dependency injection is to make every dependency a parameter of the function.

At the moment, our createUser function relies on entities outside of its parameters; this includes the create function and the ValidationError class. If we were to use dependency injection, we'd modify our createUser function to have the following structure:

function createUser(req, res, db, create, ValidationError) {  create(req)    .then(onFulfilled, onRejected)    .catch(...)}

Then, we would be able to inject the following dependencies from our tests:

...import ValidationError from '../../../validators/errors/validation-error';import createUser from '.';const generateCreateStubs = {  success: () => stub().resolves({ _id: 'foo'})}describe('create', ...

Get Building Enterprise JavaScript Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.