Photo by Irvan Smith on Unsplash

How many times you are in the following position where you have a function that depends on outer dependencies or global objects (like window, fetch, document…)

function doSomething(oneParam, callback) {

oneDependency.doSomethingElse();

fetch('resource/from/somewhere').then(callback)

}

Now, when you are trying to test this piece of code, how do you control the binding of the two dependencies on oneDepenency and fetch ? The answer is dependency injection + factoryMethod Here is how:

import { oneDependency } from './somewhere/somefile'; const doSomething = (oneParam, callback) => {

const generatedValue = oneDependency.doSomethingElse(oneParam);

// Let your mind to fly

return fetch('api/' + generatedValue).then(callback);

} export const doSomethingFactory = (oneDependency, fetch) => {

return doSomething.bind(null, oneDependency, fetch);

} import { doSomethingFactory } from './path/to/your/factory'; describe('DoSomething test suite', () => {

let service, fakeOneDependency, fakeFetch; it('Should be defined', (done) => {

// Given fake dependencies

fakeOneDependency = { doSomethingElse: () => ({mock: 'value'})};

fakeFetch = () => ({ then: () => ({fake: 'object'})});

// When

service = doSomethingFactory(fakeDependency, fakeFetch);

// Then

service('the oneParam value', (response) => {

expect(response.fake).toEqual('object');

});

});

})

By doing this you have total control on you test to provide the behavior that drives the right expectation you have about your code, this is the extremely easy way to improve and sanitize your testing set.

Code coverage BTW will be happy too! ;)