简体   繁体   English

单元测试Redux操作-Thunk未定义

[英]Unit Test Redux Action - Thunk Undefined

Wondering if someone can point out what I expect is a stupid mistake. 想知道是否有人可以指出我的期望是一个愚蠢的错误。

I have an action for user login. 我有一个用于用户登录的操作。

I'm trying to test this action, I've followed the redux documentation as well as the redux-mock-store documentation however I keep getting an error as follows: 我正在尝试测试此操作,我遵循了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)

My test code is as follows: 我的测试代码如下:

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();
            });
        })
    })
});

I've double checked both redux-thunk and redux-mock-store are included in my npm dev dependencies as well as deleteing the node_modules directory and reinstalling them all with npm install. 我已经双重检查了redux-thunk和redux-mock-store都包含在我的npm dev依赖项中,以及删除了node_modules目录并使用npm install重新安装了它们。

Can anyone see what's going wrong? 谁能看到发生了什么事情?

Thanks 谢谢

EDIT : 编辑

It seems i'm doing something fundamentally wrong, I've tried to simplify it almost back to a clean slate to find where the problem is introduced. 看来我在做根本上是错误的事情,我试图将其简化到几乎完全可以解决问题的根源。

Even with this test: 即使进行此测试:

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

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

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

Against this: 反对:

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

I'm getting an undefined error: 我收到一个未定义的错误:

  ● 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)

yes, according to that error, seems you have a problem with module dependencies. 是的,根据该错误,看来您的模块依赖项有问题。 Take a look at your webpack configuration. 看一下您的webpack配置。

Concerning the redux-mock-store , I suggest you to create a helper for future testing needs: 关于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)
}

and you will include it in your test cases and use like that: 并将其包含在测试用例中,并按以下方式使用:

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

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

If you wont test redux with thunk you can use redux-thunk-tester module for it. 如果您不会使用thunk测试redux,则可以使用redux-thunk-tester模块。

Example: 例:

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}));
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM