单元测试Redux Action - Thunk Undefined

问题描述 投票:2回答:2

想知道是否有人可以指出我所期望的是一个愚蠢的错误。

我有一个用户登录操作。

我正在尝试测试此操作,我已经遵循redux文档以及redux-mock-store文档但是我一直收到如下错误:

TypeError: Cannot read property 'default' of undefined

      4 | import thunkMiddleware from 'redux-thunk'
      5 | 
    > 6 | const middlewares = [thunkMiddleware] // add your middlewares like `redux-thunk`
        |                      ^
      7 | const mockStore = configureStore(middlewares)
      8 | 
      9 | describe("userActions", () => {

      at Object.thunkMiddleware (actions/user.actions.spec.js:6:22)

我的测试代码如下:

import {userActions} from "./user.actions";
import {userConstants} from "../constants/user.constants";
import configureStore from 'redux-mock-store'
import thunkMiddleware from 'redux-thunk'

const middlewares = [thunkMiddleware] // add your middlewares like `redux-thunk`
const mockStore = configureStore(middlewares)

describe("userActions", () => {
    describe("login", () => {
        it(`should dispatch a ${userConstants.LOGIN_REQUEST}`, () =>{
            const store = mockStore({});
            return store.dispatch(userActions.login("someuser", "somepassword")).then(() => {
                expect(store.getState().loggingIn).toBeTruthy();
            });
        })
    })
});

我已经仔细检查了redux-thunk和redux-mock-store都包含在我的npm dev依赖项中,以及删除node_modules目录并使用npm install重新安装它们。

任何人都可以看到出了什么问题?

谢谢

编辑:

看来我做了一些从根本上说错误的事情,我试图将它简化为一个干净的平板,以找出引入问题的地方。

即使有这个测试:

import authentication from "./authentication.reducer";
import { userConstants } from "../constants/user.constants";

describe("authentication reducer", () => {

    it("is a passing test", () => {
        authentication();
        expect("").toEqual("");
    });
});

反对这个:

function authentication(){
    return "test";
}
export default authentication

我收到一个未定义的错误:

  ● authentication reducer › is a passing test

    TypeError: Cannot read property 'default' of undefined

       6 | 
       7 |     it("is a passing test", () => {
    >  8 |         authentication();
         |         ^
       9 |         expect("").toEqual("");
      10 |     });

      at Object.<anonymous> (reducers/authentication.reducer.spec.js:8:9)
javascript reactjs react-native redux react-redux
2个回答
0
投票

是的,根据该错误,您似乎遇到了模块依赖性问题。看看你的webpack配置。

关于redux-mock-store,我建议你为未来的测试需求创建一个帮助器:


import configureStore from 'redux-mock-store'
import thunk from 'redux-thunk'

export default function(middlewares = [thunk], data = {}) {
  const mockedStore = configureStore(middlewares)

  return mockedStore(data)
}

并且您将它包含在您的测试用例中并使用如下:

beforeEach(() => {
  store = getMockStore()
})

afterEach(() => {
  store.clearActions()
})


0
投票

如果你不用thunk测试redux,你可以使用redux-thunk-tester模块。

例:

import React from 'react';
import {createStore, applyMiddleware, combineReducers} from 'redux';
import {asyncThunkWithRequest, reducer} from './example';
import ReduxThunkTester from 'redux-thunk-tester';
import thunk from 'redux-thunk';

const createMockStore = () => {
  const reduxThunkTester = new ReduxThunkTester();

  const store = createStore(
    combineReducers({exampleSimple: reducer}),
    applyMiddleware(
      reduxThunkTester.createReduxThunkHistoryMiddleware(),
      thunk
    ),
  );

  return {reduxThunkTester, store};
};

describe('Simple example.', () => {
  test('Success request.', async () => {
    const {store, reduxThunkTester: {getActionHistoryAsync, getActionHistoryStringifyAsync}} = createMockStore();

    store.dispatch(asyncThunkWithRequest());

    const actionHistory = await getActionHistoryAsync(); // need to wait async thunk (all inner dispatch)

    expect(actionHistory).toEqual([
      {type: 'TOGGLE_LOADING', payload: true},
      {type: 'SOME_BACKEND_REQUEST', payload: 'success response'},
      {type: 'TOGGLE_LOADING', payload: false},
    ]);

    expect(store.getState().exampleSimple).toEqual({
      loading: false,
      result: 'success response'
    });

    console.log(await getActionHistoryStringifyAsync({withColor: true}));
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.