Rewire: TypeError: Cannot read property 'data' of undefined

Rewire: TypeError: Cannot read property 'data' of undefined

为了进行单元测试,我正在使用 rewire 导入我的 react/flux 商店。 这是测试文件的样子:

'use strict';

import {expect} from 'chai';

const rewire = require('rewire');
let SessionStore;

describe.only('Session Store', () => {
  beforeEach(() => {
    SessionStore = rewire('../../app/stores/SessionStore');
  });

  it('should ....', () => {
    expect(1).to.equal(1);
  });
});

当 运行 测试时,它向我显示无法读取未定义的 data 的错误:

TypeError: Cannot read property 'data' of undefined
  at eval (eval at <anonymous> (path/tests/stores/SessionStore.js:2346:2), <anonymous>:1:546)
  at eval (eval at <anonymous> (path/tests/stores/SessionStore.js:2346:2), <anonymous>:1:677)
  at Object.eval (eval at <anonymous> (path/tests/stores/SessionStore.js:2346:2), <anonymous>:177:9)
  at Object.eval (eval at <anonymous> (path/tests/stores/SessionStore.js:2346:2), <anonymous>:178:30)
  at Object.<anonymous> (path/tests/stores/SessionStore.js:2346:2)
  at rewire (eval at <anonymous> (path/tests/stores/SessionStore.js:2340:2), <anonymous>:10:35)
  at Context.eval (eval at <anonymous> (path/tests/stores/SessionStore.js:535:2), <anonymous>:50:20)

有人知道如何解决这个问题吗?

PS。有关更多信息,这是我正在使用的商店:

SessionStore.dispatchToken = AppDispatcher.register(function(payload) {
  const action = payload.action;

  switch (action.type) {
    case ActionTypes.REQUEST_SESSION:
      _isDatafetching = true;
      SessionStore.emitChange();
      break;

    case ActionTypes.REQUEST_SESSION_SUCCESS:
      _isRequested = true;
      _isDatafetching = false;
      _isSessionValid = true;
      _currentUserId = action.response.data.user_id;
      SessionStore.emitChange();
      break;

    case ActionTypes.REQUEST_SESSION_ERROR:
      _isRequested = true;
      _isSessionValid = false;
      SessionStore.emitChange();
      break;

    default:
      // noop
  }
});

export default SessionStore;

我去了同样的错误信息。

我用 ES6 编写代码,运行 使用 karma 进行测试。

我使用的所有重新布线模块都无法解决错误。

我终于安装了 babel-rewire 插件(https://www.npmjs.com/package/babel-rewire-plugin),在 webpack 中配置后,一切顺利。