I am having a problem with stubbing/testing function that is using fetch.
Using simple example:
export const clickTimeseries => {
return fetch('...url...')
.then(response => {
if(response.status == 200)
return response.json()
else
throw 'something'
})
.then(json => {
return {
success: true,
data: json,
}
})
.catch(err => {
return {
success: false,
error: err,
}
})
}
And my test:
import { expect } from 'chai'
import sinon from 'sinon'
import Promise from 'es6-promise'
Promise.polyfill()
import 'whatwg-fetch'
import clickTimeseries from './above'
const jsonOK = body => {
const mockResponse = new Response(JSON.stringify(body), {
status: 200,
headers: {
'Content-type': 'application/json'
}
})
return Promise.resolve(mockResponse)
}
describe('APIs', () => {
describe('Click timeseries', () => {
it('builds a correct data on success', () => {
sinon.stub(window, 'fetch').returns(jsonOK({stuff: [1,2,3]}))
expect(clickTimeseries()).to.eq({
success: true,
data: {stuff: [1,2,3]}
})
})
})
})
I am getting error:
expected { Object (, _state, ...) } to equal { success: true, data: {stuff: [ 1, 2, 3, 4 ] }}
It looks like spendTimeseries
returns promise, instead of the result of calling both then
blocks.
How would you have to setup your test to have it pass?