我非常高兴地测试异步Redux操作,但我完全被一个非常简单的情况所困扰。这是我的功能:
//actions.js
export const fetchInfo = (credentials) => {
return (dispatch) => {
dispatch(asyncRequest())
const fetchConfig = {
method: 'POST',
body: JSON.stringify({
email: credentials.email,
token: credentials.token
})
}
return fetch('api/info', fetchConfig)
.then(response => {
if (response.status === 200) {
return response.json()
.then((json) => {
console.log(json)
dispatch(receiveInfoSuccess(json))
} else if (response.status === 401) {
dispatch(push('/signin'))
},
error => {
dispatch(receiveInfoFailure(error))
})
}
}
如果我测试我的状态401的情况,一切都很好,但由于某种原因,我无法让测试跑过response.json()
。这是我的测试:
it('should use fetchInfo to dispatch relevant action creators', (done) => {
const credentials = {"email": "e@d.com", "token": "djbsdJ"}
const fetchReturnVal = {
status: 200,
headers: {"Content-Type": "application/json"},
body: {
"id": "kjbsdf"
}
}
fetchMock.post('api/info', fetchReturnVal)
const expectedActions = [
{type: 'ASYNC_REQUEST'},
{type: 'RECEIVE_INFO_SUCCESS',
payload: {
id: 'kjbsdf'
}
}
]
function mockDispatch(action) {
const expectedAction = expectedActions.shift()
expect(action).toEqual(expectedAction)
if (!expectedActions.length) {
done()
}
}
actions.fetchLogin(credentials)(mockDispatch)
})
测试总是超时Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
,代码永远不会进入.then
块。
如何解决response.json
承诺?我尝试过在fetch返回值中包含以下键的内容:
json: () => {
return new Promise((resolve, reject) => {
resolve({"id": "example"})
})
}
....但这也只是超时