Mocha测试未访问全局变量

Global Variables not being accessed by Mocha tests

本文关键字:全局变量 访问 测试 Mocha      更新时间:2023-09-26

我得到一个ReferenceError:未定义NC_SETTINGS。

"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可能有效,是因为它适用于导入同构获取,我也遇到了类似的问题。

有没有一种方法可以将全局变量导入MochaJs,这样我的操作就可以访问NC_SETTINGS?

我应该提到store.dispatch(Actions.addPasswordResetRequest())链接到一个操作文件,该文件分派到js文件中的api调用。末尾的js文件是NC_SETTINGS所在的位置,也是调用错误的位置。在浏览器中,这很好用。

有没有一种方法可以列出全局变量并在Mocha中测试时添加它们?

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

global.NC_SETTINGS = ...

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

然而,由于许多原因,全局变量是您想要避免的。相反,您可能想要进行某种依赖性注入。两种可能性是:

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