异步/等待返回承诺 代替值

问题描述 投票:0回答:1

我在行动中提出要求。从需要从模拟redux存储返回值的api中提取。我有它在redux模拟存储调度动作时启动该请求,但是我似乎无法正确显示这些值。

我收到错误Promise { <pending> }。异步/等待返回承诺待处理而不是值。

例如:

simpleActions.js

export const fetchTodos = () => {
    return async (dispatch) => {
        const response = await axios.get('https://tutorialzine.com/misc/files/example.json');
        dispatch({ type: POST_CONNECTION, payload: response.data });
       }
}

simpleAction.test.js

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

describe('async actions', () => {
  afterEach(() => {
    fetchMock.restore()
  })

  it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
    fetchMock.getOnce('/todos', {
      body: { todos: ['do something'] },
      headers: { 'content-type': 'application/json' }
    })

    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something'] } }
    ]
    const store = mockStore({ todos: [] })

    // It is always return promise <pending> instead of values when call async/await actions
    // I have trouble when call this line.
    const dispatchStored = store.dispatch(actions.fetchTodos());

    return dispatchStored.then(() => {

      expect(store.getActions()).toEqual(expectedActions)
    })
  })
})

如何在模拟存储分派操作中调用或模拟需要返回值而不是未处理的promise的异步/等待函数。任何帮助将不胜感激。

typescript unit-testing redux jest redux-mock-store
1个回答
0
投票

您不返回已解决的承诺:

export const fetchTodos = () => {
  return async (dispatch) => {
    const response = await axios.get('https://tutorialzine.com/misc/files/example.json');
    dispatch({
      type: POST_CONNECTION,
      payload: response.data
    });
    return response;  // Return response
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.