我有一个使用NodeJS编写的REST应用程序正在Heroku上运行。我已经为本地开发设置了.env文件,并且每当我运行foreman在本地提供我的应用程序时,它都可以正常工作。当我将应用程序部署到我的Heroku服务器时,应用程序也可以正常运行。
我正在尝试使用Mocha/Supertest/should/assert编写我的应用程序的单元测试。当我通过Mocha运行我的应用程序时,它不会加载.env文件以获取我的环境变量-在我的情况下是PSQL数据库的URL。结果,所有涉及DB I/O的测试都会超时。
我一直在搜索解决方案,但似乎找不到任何有用的东西。
这是一些样例代码:
app.js:
var application_root = __dirname,
express = require("express"),
port = process.env.PORT || 4482;
pg = require('pg').native,
client = new pg.Client(process.env.DATABASE_URL);
// Connect To DB
client.connect();
(...)
app.get('/api', function (req, res) {
res.send('PS API is running');
});
app.get('/', function (req, res) {
res.send('PS API is running');
});
(...)
// Read Users
app.get('/users', function (req,res) {
user.readUsers(res,client);
});
(...)
// Launch server
console.log('Listening on port: '+ port);
app.listen(port);
module.exports = app;
userTest.js
var request = require('supertest');
var assert = require('assert');
var app = require('app.js');
var should = require('should');
describe('Get /', function(){
it('should respond OK',function(done){
request(app)
.get('/')
.end(function(err, res){
res.status.should.equal(200);
done(err);
});
});
});
describe('Get /api', function(){
it('should respond OK',function(done){
request(app)
.get('/api')
.end(function(err, res){
res.status.should.equal(200);
done(err);
});
});
});
// Getting All Users
describe('Get /users', function(){
it('should respond OK',function(done){
request(app)
.get('/users')
.end(function(err, res){
res.status.should.equal(200);
done(err);
});
});
});
.env
== LOCAL DB ==
DATABASE_URL=MY_DB_URL
HEROKU_POSTGRESQL_GOLD_URL=MY_DB_URL
PATH=bin:node_modules/.bin:/usr/local/bin:/usr/bin:/bin
我运行mocha test
的输出结果是什么?
Listening on port: 4482
․․Getting all users
․
2 passing (2 seconds)
1 failing
1) Get /users should respond OK:
Error: timeout of 2000ms exceeded
at Object.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:165:14)
at Timer.list.ontimeout (timers.js:101:19)
当我将process.env.DATABASE_URL
替换为我硬编码的PSQL本地URL时,所有测试都通过了。所以很明显,mocha没有读取.env文件。
我也尝试过向Mocha传递环境变量,但效果不佳。请问有没有正确的方法让Mocha从.env文件中读取我的环境变量?