Redux模拟存储仅在调度多个动作时才返回一个动作

时间:2018-12-10 10:56:34

标签: reactjs redux redux-mock-store

我正在尝试模拟此axios呼叫:

import io
import os
import re


# the end-of-line chars, separated by a `|` (logical OR)
EOL_REGEX = b'\r\n|\r|\n'  


def readlines(fio, size):
    buf = bytearray(4096)
    while True:
        if fio.tell() >= size:
            break               
        fio.readinto(buf)            
        for line in re.split(EOL_REGEX, buf):
            yield line

size = os.path.getsize("test.pdf")
with io.FileIO("test.pdf") as fio:
    for line in readlines(fio, size):
         ...

成功调用后,应该分派动作创建者fetchCountryPending()和fetchCountryFullfilled(country)。当我这样嘲笑时:

export const fetchCountry = (query) => {
  return dispatch => {
    dispatch(fetchCountryPending());
    return axios.get(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`)
      .then(response => {
        const country = response.data;
        dispatch(fetchCountryFulfilled(country));
      })
      .catch(err => {
        dispatch(fetchCountryRejected());
        dispatch({type: "ADD_ERROR", error: err});
      })
  }
}

第二个期望失败,console.log(actions)仅显示一个动作的数组,但它应包含两个动作,即fetchCountryPending和fetchCountrySuccess。当我登录(“已调度”)时,它表明第二个操作正在终端中调度。

2 个答案:

答案 0 :(得分:1)

您可以尝试使它阻止异步并分派操作吗?我相信测试会在您的get请求返回值之前运行

答案 1 :(得分:0)

我无法获得then(()=> {})块来工作,但我能够等待该函数并使它异步:

  it('dispatches FETCH_COUNTRY_FULFILLED after axios request', async () => {
    const query = 'Aland Islands'
    mock.onGet(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`).replyOnce(200, country)
    await store.dispatch(countryActions.fetchCountry(query))
    const actions = store.getActions()
    console.log(actions)
    expect(actions[0]).toEqual(countryActions.fetchCountryPending())
    expect(actions[1]).toEqual(countryActions.fetchCountryFulfilled(country))
  });
});