We can create different stubs that return different results, each mimicking the possible return values of the create function:
import { stub } from 'sinon';
import ValidationError from '../../../validators/errors/validation-error';
const createStubs = {
success: stub().resolves({ _id: 'foo'}),
validationError: stub().rejects(new ValidationError()),
otherError: stub().rejects(new Error()),
}
Now, if we invoke createStubs.success(), it will always resolve to the { _id: 'foo'} object; therefore, we can use this stub to test for scenarios where the req object we pass into the createUser function is valid. Likewise, we can use createStubs.validationError() to mimic a situation where the req object causes createUser to reject with ValidationError.
Now, we know how to stub out the create function, but how do we actually replace it inside the createUser function? When testing the createUser function, the only variables we can change in our test are the parameters we pass into the function, and the createUser method accepts only three parameters: req, res, and db.
There are two approaches to this: dependency injection and monkey patching.