【问题标题】:Global Variables not being accessed by Mocha testsMocha 测试未访问全局变量
【发布时间】:2016-01-11 17:09:59
【问题描述】:

我收到一个 ReferenceError: NC_SETTINGS is not defined。

"use strict";


import forOwn from 'lodash/object/forOwn';
import { assert, expect, should } from 'chai';
import { spy } from 'sinon';
import { applyMiddleware } from 'redux';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import {
    REQUEST_ADD_PASSWORD_RESET_REQUEST,
    REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS,
    REQUEST_ADD_PASSWORD_RESET_REQUEST_FAILURE
} from 'actions/types';
import nock from 'nock';
import Actions from 'actions';
import fetch from 'isomorphic-fetch';

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

var NC_SETTINGS = require('/home/tai/Gravitate/nc-app/taimoor/settings').NC_SETTINGS;
describe('forgot password async actions', () => {
    afterEach(()=> {
        nock.cleanAll();
    });

    //mockActions();
    //console.log(Actions.addPasswordResetRequest().addPasswordResetRequestAPI());
    it('should show a request for a password reset and that it succeeded ', (done) => {

        console.log(NC_SETTINGS);
        nock('http://localhost:8080/')
        .post('/password-reset-requests')
        .reply(200);
        var email = "test@email.com";
        const expectedActions= [
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ];
        const store = mockStore({}, expectedActions, done);
        store.dispatch(Actions.addPasswordResetRequest());
        //unMockActions();
        //
        //console.log(actions);
        //expect(actions.addPasswordResetRequest("email")).to.equal(expectedAction);

  });

});

所以当我 console.log NC_SETTINGS 时,它确实显示了。但是,当我运行 store.dispatch(Actions.addPasswordResetRequest) 时,我得到 NC_SETTINGS 未定义。我认为导入 NC_SETTINGS 可能会起作用的原因是因为它适用于导入 isomorphic-fetch,我遇到了类似的问题。

有没有办法将全局变量导入 MochaJs,以便我的操作可以访问 NC_SETTINGS?

我应该提到 store.dispatch(Actions.addPasswordResetRequest()) 链接到一个动作文件,该文件调度到一个 js 文件中的 api 调用。最后的那个 js 文件是 NC_SETTINGS 所在的位置,也是调用错误的位置。在浏览器中,这工作正常。

有没有办法在 Mocha 中测试时获得全局变量列表并添加它们?

【问题讨论】:

    标签: javascript reactjs mocha.js chai redux


    【解决方案1】:

    不要这样做,但你可以使用:

    global.NC_SETTINGS = ...
    

    将其设置为 nodejs 全局变量。这应该在Actions 中获取。

    但是,出于多种原因,您需要避免使用全局变量。相反,您可能想做某种依赖注入。两种可能:

    1. Actions 实现为一个类,并在使用它的地方实例化它,并将NC_SETTINGS 作为构造参数传递。
    2. 使用rewire 模块。在这种情况下,NC_SETTINGS 可以是 Actions 模块中的顶级变量,但不是全局变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 2020-09-07
      • 2011-10-06
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多