Skip to content

Instantly share code, notes, and snippets.

@mateuszsokola
Last active July 30, 2017 17:56
Show Gist options
  • Save mateuszsokola/2fc2cdc3b5c3d6fdbbb63cb500bacd12 to your computer and use it in GitHub Desktop.
Save mateuszsokola/2fc2cdc3b5c3d6fdbbb63cb500bacd12 to your computer and use it in GitHub Desktop.

Testing with Dependency Injection

DI is a design pattern that allows us to inject dependencies into components. It's about transmiting instances of objects into other objects, which use them (eg. as a parameters). DI makes testing easier as it makes mocking easy. Mocked dependencies can be injected into the tested component.

const restHelperFactory = ({ fetch }) => {
return (url) => {
return fetch(url)
.then(response => response.json())
.then(cities => cities.map(
city => ({ id: city.id, label: city.name })
));
}
}
export default restHelperFactory;
import restHelperFactory from '../rest-helper'
const testData = [{
id: 1,
name: 'Amburgo',
admin_area: 'Hamburg',
country: 'Deutschland'
}, {
id: 2,
name: 'Wedding',
admin_area: 'Whatever',
country: 'Deutschland'
}];
it('calls fetch with expected url', () => {
const fetch = (url) => {
expect(url).toEqual('/v1/mock')
return Promise.resolve({
json: () => Promise.resolve(testData)
});
};
const restHelper = restHelperFactory.bind(restHelperFactory, fetch);
restHelper('/v1/mock');
})
it('parses the response as expected', () => {
const expectedResponse = [{
id: 1,
label: 'Amburgo'
}, {
id: 2,
label: 'Wedding'
}]
const fetch = (url) => {
return Promise.resolve({
json: () => Promise.resolve(testData)
})
}
const restHelper = restHelperFactory.bind(restHelperFactory, fetch)
restHelper('/v1/mock').then(
cities => expect(cities).toEqual(expectedResponse)
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment