【发布时间】:2017-06-05 13:07:41
【问题描述】:
我在使用 fetch 的存根/测试函数时遇到问题。
使用简单的例子:
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,
}
})
}
我的测试:
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]}
})
})
})
})
我收到错误:
expected { Object (, _state, ...) } to equal { success: true, data: {stuff: [ 1, 2, 3, 4 ] }}
看起来spendTimeseries 返回了promise,而不是调用两个then 块的结果。
你必须如何设置你的测试才能让它通过?
【问题讨论】:
标签: javascript sinon fetch-api