如何使用fetch-mock调度存储操作?

时间:2018-06-03 23:05:24

标签: redux redux-mock-store fetch-mock

我需要帮助用fetch-mock测试redux fetch调用。应该在dashboardActions.js中使用函数requestPredict()来获取api调用,然后调用resultReady(data)。但是当我运行测试时,我在下面得到了一个失败的测试。

Expected value to equal:
[{"type": undefined}, {"data": {"hello": "world"}, "type": undefined}]
Received:
[{"type": "DASHBOARD_RESULT_LOADING"}, {"result": {"result": {"hello": "world"}}, "type": "DASHBOARD_RESULT_READY"}]

dashboardActions.js

function resultReady(json) {
 return {
    type: DASHBOARD_RESULT_READY,
 result: camelizeKeys(json)
 };
}

export function requestPredict(subPath, params) {
 let url = `${process.env.API_URL}/predict/${subPath}`;
 const requestParams = {
 method: 'post',
 credentials: 'include',
 body: JSON.stringify(params),
 headers: {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${process.env.API_AUTH_TOKEN}`
 }
};

return async (dispatch, getState) => {
return fetch(url, requestParams)
  .then(response => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw Error(response.statusText);
    }
  })
  .then(data => dispatch(resultReady(data)));
 };
}

dashboardActions.test.js

const mockData = { 
   "hello": "world"
 }

describe('action creators', () => {

afterEach(() => {
  fetchMock.reset()
})

it('should create DASHBOARD_RESULT_READY', () => {
fetchMock.post('*', { result: { "hello": 'world'} });

const expectedActions = [
  { type: actions.DASHBOARD_RESULT_LOADING },
  { type: actions.DASHBOARD_RESULT_READY, data: mockData }
]

const store = mockStore({
  result: {}
})

return store.dispatch(actions.requestPredict())
  .then((data) => {
    expect(store.getActions()).toEqual(expectedActions)
  })
 })
})

0 个答案:

没有答案