TypeError:无法读取未定义的属性“ hasError”

时间:2018-07-16 11:12:15

标签: reactjs react-native react-redux jestjs

我正在使用jest来进行本机测试和Redux。当执行我得到的测试文件时

  

TypeError:无法读取未定义的属性“ hasError”

此错误。我不知道如何将值发送到redux。任何人都请帮帮我。

错误代码是

FAIL  __tests__\jest\LoginScreen.test.js (6.801s)
  test
    × renders correctly (614ms)

  ● test › renders correctly

    TypeError: Cannot read property 'hasError' of undefined

      219 | const mapStateToProps = (state) => {
      220 |     return {
    > 221 |         hasError: state.LoginReducer.hasError,
      222 |         error: state.LoginReducer.error
      223 |     }
      224 | }

      at Function.mapStateToProps [as mapToProps] (src/screens/login/loginScreen.js:221:38)
      at mapToPropsProxy (node_modules/react-redux/lib/connect/wrapMapToProps.js:54:92)
      at Function.detectFactoryAndVerify (node_modules/react-redux/lib/connect/wrapMapToProps.js:63:19)
      at mapToPropsProxy (node_modules/react-redux/lib/connect/wrapMapToProps.js:54:46)
      at handleFirstCall (node_modules/react-redux/lib/connect/selectorFactory.js:37:18)
      at pureFinalPropsSelector (node_modules/react-redux/lib/connect/selectorFactory.js:85:81)
      at Object.runComponentSelector [as run] (node_modules/react-redux/lib/components/connectAdvanced.js:43:25)
      at Connect.initSelector (node_modules/react-redux/lib/components/connectAdvanced.js:195:23)
      at new Connect (node_modules/react-redux/lib/components/connectAdvanced.js:136:15)
      at constructClassInstance (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3716:20)

我的测试代码是

import "../jest";
import LoginScreen from "../../src/screens/login/loginScreen";
import { shallow } from "enzyme";
import configureMockStore from "redux-mock-store";
const mockStore = configureMockStore();

// Note: test renderer must be required after react-native.
describe("test", () => {
  let wrapper, store;
  beforeEach(() => {
    const initialState = {
      hasError: false,
      error: {
        display_message: "",
        data: null
      }
    };
    store = mockStore(initialState);
  });
  test("renders correctly", () => {
    const tree = renderer
      .create(
        <Provider store={store}>
          <LoginScreen />
        </Provider>
      )
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});

2 个答案:

答案 0 :(得分:0)

在您的redux状态下,显然没有保存任何名为LoginReducer的内容。您是否有一个使用该确切名称的减速器?

请参阅Redux官方文档上的combineReducers指南以了解如何使用它。您需要使用combineReducers方法将LoginReducer添加到您的状态。

答案 1 :(得分:0)

@KevinCooper在CombineReducer中,并没有提到如何开玩笑地进行估值。我同样有疑问如何将值发送到玩笑的redux存储中