如果缺少参数(例如 DB URI),我的 Express 服务器会抛出错误。我想在 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 应用程序抛出错误时,错误会被抛出到控制台,并且测试失败(事实上,它并没有结束)。
<小时/>我遇到的另一个问题是 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;
});
关于node.js - Mocha 测试 Express 启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758361/