如何使用env param测试nodejs的index.js?

时间:2019-02-08 01:26:59

标签: node.js unit-testing sinon

我的节点js具有以下index.js。当我运行覆盖范围时,它告诉我此行未采用其他路径:if(enableCompression) {

我的.env默认设置为process.env.ENABLE_COMPRESSION = 'true'

如何测试该路径?我尝试在测试用例中设置process.env.ENABLE_COMPRESSION = 'false',但由于服务器已启动,因此它不会再次重新运行index.js。

我该怎么做?我正在使用sinon进行单元测试。

index.js:

require('dotenv').config({ path: require('find-config')('.env') });

const PORT = process.env.PORT;
const ENABLE_COMPRESSION = process.env.ENABLE_COMPRESSION;

let express = require('express');
let compression = require('compression');

//logging
let log4js = require('log4js');
log4js.configure('./config/log4js.json');

//Please do not remove this line, since CLI uses this line as guidance to import new controllers
let app = express();

let enableCompression = ENABLE_COMPRESSION === "true";

if(enableCompression) {
    app.use(compression());
}

app.use(log4js.connectLogger(log4js.getLogger("app"), { level: 'auto' }));

let log = log4js.getLogger("api-app");

//importing route
let routes = require('./api/rest/apiRest');

//register the route
routes(app);

//reached here throw error 404, means no routes to handle inc. request
app.use((req, res, next) => {
    const error = new Error('Not found');
    error.status = 404;

    next(error);
});

// catch errors
app.use((error, req, res, next) => {

    log.error("ERROR - " + req.url + " - " + error.message);

    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    });
});

//start application
module.exports = app.listen(PORT, () => {
    log.info('API server started on: ' + PORT);
});

0 个答案:

没有答案