首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用艾灸测试redux异步方法

用艾灸测试redux异步方法
EN

Stack Overflow用户
提问于 2018-12-18 19:26:25
回答 1查看 858关注 0票数 2

我是新来的,我的头发拔出我的头发,试图得到一个基本的测试,以工作与复古和艾灸。

API只是axios,设置了一些自定义头。

我在post方法上出现了一个错误: TypeError:无法读取未定义的属性‘of’

我的方法:

代码语言:javascript
复制
const login = ({username, password}) => (dispatch) => {
  dispatch(actions.loginRequested());
  return API.post(`curavi/v2/authentication`, {username, password})
    .then(response => dispatch(actions.loginSuccess(response.data.payload)))
    .catch((error) => errorHandler(dispatch, error.response));
};

我的测试用例:

代码语言:javascript
复制
describe('login', () => {

  beforeEach(function () {
    // import and pass your custom axios instance to this method
    moxios.install(API)
  });

  afterEach(function () {
    // import and pass your custom axios instance to this method
    moxios.uninstall(API)
  });

  test('calls loginSuccess when the response is successful', () => {
    const store = mockStore();

    const mockData = {
      data: { payload: 'yay' }
    };

    moxios.wait(() => {
      const request = API.requests.mostRecent();
      request.respondWith({
        status: 200,
        response: mockData
      });
    });

    const expectededActions = [
      {type: types.LOGIN_REQUESTED},
      {type: types.LOGIN_SUCCESS, payload: 'yay'}
    ];

    actions.loginRequested.mockReturnValue({type: types.LOGIN_REQUESTED});
    actions.loginSuccess.mockReturnValue({type: types.LOGIN_SUCCESS, payload: 'yay'});
    actions.loginFail.mockReturnValue({type: types.LOGIN_FAIL, message: 'boo'});

    return store.dispatch(operations.login({username: 'theuser', password: 'thepassword'}))
      .then(() => {
        expect(store.getActions()).toEqual(expectededActions);

        expect(API.post).toHaveBeenCalledWith('curavi/v2/authentication',
          {username: 'theuser', password: 'thepassword'});
      });
  })
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-18 22:42:05

您确定按照您的建议在TypeError中获得login吗?这是没有意义的;如果API不是axios实例,您就会得到这个错误,在这种情况下,API.post()可以返回未定义的值。另一方面,您的测试不起作用的原因有两个:

  • 您需要将API.requests.mostRecent()替换为moxios.requests.mostRecent()
  • 您在艾灸的等待中的功能将在0.5秒内不执行,请参见这里。如果您的测试中的返回语句是在此之前到达的,那么您的测试将只返回一个承诺。您可以选择以下操作: 测试(‘.’,=> { // .const结果=等待expect(store.getActions()).toEqual(expectededActions);store.dispatch( operations.login({ username:'theuser',密码:'thepassword',});

您还应该确保正确地设置商店:

代码语言:javascript
复制
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';

const middlewares = [thunk];
const mockStore = configureStore(middlewares);

// use your store inside your tests
const store = mockStore();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53839786

复制
相关文章

相似问题

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