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.
Last active
July 30, 2017 17:56
-
-
Save mateuszsokola/2fc2cdc3b5c3d6fdbbb63cb500bacd12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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