摩卡测试快递启动
Mocha test express startup
如果缺少参数(例如 DB URI),我的快递服务器会抛出错误。我想在 Mocha 中测试它是否确实抛出了错误,但我不知道如何让 Mocha 做到这一点。
if(!parameters.db) {
throw new Error('Please provide a db URI');
}
我有这样的测试设置:
it('Throws Error when no db URI provided in production mode', function () {
expect(require('../server')).to.throw();
done();
});
当我的 Express app 抛出错误时,错误被抛到控制台,测试失败(实际上并没有结束)。
我遇到的另一个问题是,如果环境处于生产模式,Express 只会检查参数。我试图在测试套件中将流程环境设置为生产环境,但是当我 运行 它时, NODE_ENV
仍然设置为 'test'.
before(function() {
env = process.env;
// This doesn't really set the environment when I run the tests.
process.env.NODE_ENV = 'production';
});
如果您尝试测试应用程序中未处理的异常,请尝试将您的调用包装在 try/catch 中,如果未抛出错误则返回错误。
it('Throws Error when no db URI provided in production mode', function () {
let threwError = false;
try {
// create the server that throws the Error
require('../server');
} catch (err) {
threwError = true;
}
expect(threwError, 'Didn\'t throw an error, when DB URI is empty').to.be.true;
});
如果缺少参数(例如 DB URI),我的快递服务器会抛出错误。我想在 Mocha 中测试它是否确实抛出了错误,但我不知道如何让 Mocha 做到这一点。
if(!parameters.db) {
throw new Error('Please provide a db URI');
}
我有这样的测试设置:
it('Throws Error when no db URI provided in production mode', function () {
expect(require('../server')).to.throw();
done();
});
当我的 Express app 抛出错误时,错误被抛到控制台,测试失败(实际上并没有结束)。
我遇到的另一个问题是,如果环境处于生产模式,Express 只会检查参数。我试图在测试套件中将流程环境设置为生产环境,但是当我 运行 它时, NODE_ENV
仍然设置为 'test'.
before(function() {
env = process.env;
// This doesn't really set the environment when I run the tests.
process.env.NODE_ENV = 'production';
});
如果您尝试测试应用程序中未处理的异常,请尝试将您的调用包装在 try/catch 中,如果未抛出错误则返回错误。
it('Throws Error when no db URI provided in production mode', function () {
let threwError = false;
try {
// create the server that throws the Error
require('../server');
} catch (err) {
threwError = true;
}
expect(threwError, 'Didn\'t throw an error, when DB URI is empty').to.be.true;
});