首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单元测试Redux异步操作

单元测试Redux异步操作
EN

Stack Overflow用户
提问于 2017-05-16 02:24:13
回答 1查看 586关注 0票数 2

我正在尝试将单元测试用例添加到我的redux操作。

我试过thisthis & this

我在我的操作中使用了thunkpromise-middleware

我的一个动作是这样的

代码语言:javascript
复制
export function deleteCommand(id) {
  return (dispatch) => {
    dispatch({
      type: 'DELETE_COMMAND',
      payload: axios.post(`${Config.apiUrl}delete`, { _id: id })
    })
  }
}

这个的单元测试是

代码语言:javascript
复制
import configureMockStore from "redux-mock-store"
const middlewares = [thunk, promiseMiddleware()];
const mockStore = configureMockStore(middlewares)

  it('creates DELETE_COMMAND_FULFILLED after deleting entry', (done) => {

    nock('http://localhost:8081/')
      .post('/delete',{
        _id: 1
      })
      .reply(200, {})

    const expectedActions = [{
      type: 'DELETE_COMMAND_FULFILLED',
      payload: {}
    }]

    const store = mockStore({
      command: {
        commands: []
      }
    })

    store.dispatch(actions.deleteCommand({_id: 1}).then(function () {
      expect(store.getActions())
        .toEqual(expectedActions)
      done();
    })

  })

我使用的是nock、配置了thunkredux-mock-storepromise middleware

它给了then of undefined

然后我更改了动作以返回promise,然后我得到了unhandled promise reject异常,我在动作分派调用中添加了一个catch。现在我得到了Network Error,因为它没有模拟调用。我也尝试了moxios,将axios更改为isomorphic-fetchwhatwg-fetch。似乎不起作用

我哪里做错了?

EN

回答 1

Stack Overflow用户

发布于 2020-01-09 08:51:26

我知道这是2017年的事,但也许有人会有同样的问题。

所以问题是deleteCommand内部的箭头函数

返回未定义。这就是为什么你会

它给出的

则是未定义的

redux TLDR:如果您将redux-thunk与redux-promise-middleware一起使用,则必须返回内部分派

here is the official redux-promise-middleware docs

解决方案非常简单:

选项1.在箭头函数内添加

代码语言:javascript
复制
    export function deleteCommand(id) {
      return (dispatch) => {
        return dispatch({
          type: 'DELETE_COMMAND',
          payload: axios.post(`${Config.apiUrl}delete`, { _id: id })
        })
      }
    }

选项2. 函数中删除大括号

代码语言:javascript
复制
export function deleteCommand(id) {
  return (dispatch) => 
    dispatch({
      type: 'DELETE_COMMAND',
      payload: axios.post(`${Config.apiUrl}delete`, { _id: id })
    })
}

现在你可以做

代码语言:javascript
复制
store.deleteCommand(<some id>).then(...)

一般情况下,箭头函数和返回

  • 返回纯对象

代码语言:javascript
复制
// option 1
const arrowFuncOne = () => {
  return {...someProps}
}

// option 2
const arrowFuncTwo = () => ({
   ...someProps
})

// This means that you returning an expression 
//same as

// return a result of other function
const arrowFuncCallFunOne = () => callSomeOtherFunc()
// or
const arrowCallFunkTwo = () => {return callSomeOtherFunc()}


// However
// wrong 
const arrowCallFunkNoReturn = () => {callSomeOtherFunc()}
// in this case the curly braces are just the body of the function  
// and inside this body there is no return at all
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43986386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档