【Node】【Mocha】使用mocha进行测试时全局变量无法访问

4

我想要创建一个针对Express Node应用的单元测试。我希望测试所使用的配置与生产环境中使用的不同,因此我采取以下措施。

在我的index.js文件中,我将配置加载到全局变量中,如下所示:

global.env = {};
global.env.config = require('./config/config');
// Create the server ...
server.listen(3000);

module.exports = server;

在另一个控制器 myController.js 中,我会像这样访问全局变量。
var Config = global.env.config

当我使用node index.js启动时,它能正常工作。

但当我使用mocha和proxyquire覆盖配置时:

describe('myController', function () {
    describe("#myMethod", () => {

        it("must work", (done) => {
             const config = {
                INPUT_FILE_DIR: path.resolve('../ressources/input/')
             }

             const server = proxyquire('../index.js', { './config/config': config })// error in this line
        })
    })
})

我出现了一个错误,提示说myController无法读取属性“config”。
Cannot read property 'config' of undefined

感谢您的帮助

2个回答

5
这是我会处理的方法。首先,我会将配置导出为一个函数而不是一个对象。
原因是代码将具有更好的结构和易于维护。此外,无需将配置全局公开,因为那可能会带来一些安全风险。
export const getConfig = () => {
  if(process.env.NODE_ENV==="production"){
    return require('./production.config');
  }
  return require('./default.config');
};

在我的测试文件中,我会使用sinonjs来模拟函数调用,如下所示。

const configModule = require("./config");
sinon.stub(configModule, "getConfig").returns(require('./e2e.config'));

这不是经过测试的代码,但我有点确定这种思路应该是行得通的。


4
为什么不在测试用例中使用新配置覆盖它呢?
例如:
index.js:
const express = require('express');
const server = express();
const userController = require('./userController');

global.env = {};
global.env.config = require('./config');

server.get('/api/user', userController.getUser);

if (require.main === module) {
  const port = 3000;
  server.listen(port, () => {
    console.log(`HTTP server is listening on http://localhost:${port}`);
  });
}

module.exports = server;

userController.js:

const Config = global.env.config;

const userController = {
  getUser(req, res) {
    res.json(Config.user);
  },
};

module.exports = userController;

config.js:

module.exports = {
  user: { name: 'james' },
};

userController.test.js:

const sinon = require('sinon');

describe('userController', () => {
  describe('#getUser', () => {
    it('should pass', () => {
      global.env = {};
      global.env.config = { user: { name: 'jane' } };
      const userController = require('./userController');
      const mReq = {};
      const mRes = { json: sinon.stub() };
      userController.getUser(mReq, mRes);
      sinon.assert.calledWithExactly(mRes.json, { name: 'jane' });
    });
  });
});

单元测试结果与覆盖率报告:

  userController
    #getUser
      ✓ should pass (880ms)


  1 passing (893ms)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |     100 |      100 |     100 |     100 |                   
 userController.js |     100 |      100 |     100 |     100 |                   
-------------------|---------|----------|---------|---------|-------------------

UPDATE

index.js:

// Order is matter, assign config to global firstly, then the controllers can access it.
global.env = {};
global.env.config = require('./config');

const express = require('express');
const server = express();
const userController = require('./userController');

server.get('/api/user', userController.getUser);

if (require.main === module) {
  const port = 3000;
  server.listen(port, () => {
    console.log(`HTTP server is listening on http://localhost:${port}`);
  });
}

module.exports = server;

userController.jsconfig.js与上面的相同。

index.test.js

const request = require('supertest');
const proxyquire = require('proxyquire');
const { expect } = require('chai');

describe('60990025', () => {
  it('should get user', (done) => {
    const config = { user: { name: 'jane' } };
    const server = proxyquire('./', {
      './config': config,
    });
    request(server)
      .get('/api/user')
      .expect(200)
      .end((err, res) => {
        if (err) return done(err);
        expect(res.body).to.be.eql({ name: 'jane' });
        done();
      });
  });
});

API测试结果与覆盖报告:

  60990025
    ✓ should get user (2946ms)


  1 passing (3s)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |   81.25 |       50 |      50 |   81.25 |                   
 config.js         |     100 |      100 |     100 |     100 |                   
 index.js          |   72.73 |       50 |       0 |   72.73 | 12-14             
 userController.js |     100 |      100 |     100 |     100 |                   
-------------------|---------|----------|---------|---------|-------------------

源代码:https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/60990025

该页面中包含一个链接,它指向一个名为"source code"的GitHub仓库。

myController没有直接被调用,但我通过一个get请求调用了服务器(而服务器需要该控制器)。看到问题了吗?这是一个端到端测试。 - abderrahim_05

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接