Skip to content

Instantly share code, notes, and snippets.

@shawnlknight
Created January 18, 2017 14:12
Show Gist options
  • Save shawnlknight/e107ead32ad74cc0b08ad43d280c7bcf to your computer and use it in GitHub Desktop.
Save shawnlknight/e107ead32ad74cc0b08ad43d280c7bcf to your computer and use it in GitHub Desktop.
Dependency Injection
/*
- From: funfunfunction https://www.youtube.com/watch?v=0X1Ns2NRfks&feature=em-subs_digest
- Using mocha to run tests
*/
const assert = require('assert')
function getAnimals(fetch, id) {
return fetch('http://api.animalfarmgame.com/animals/' + id)
.then(response => response.json())
.then(data => data.results[0])
}
describe('getAnimals', () => {
it('calls fetch with the correct url', () => {
const fakeFetch = url => {
assert(
url ===
'http://api.animalfarmgame.com/animals/123'
)
// fake a promise that never returns
return new Promise(function(resolve) {
})
}
getAnimals(fakeFetch, 123)
})
it('parses the response of fetch correctly', (done) => {
const fakeFetch = () => {
return Promise.resolve({
json: () => Promise.resolve({
results: [
{ name: 'fluffykins' }
]
})
})
}
getAnimals(fakeFetch, 12345)
.then(result => {
assert(result.name === 'fluffykins')
done()
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment