javascript - catch 分支缺少覆盖
问题描述
我开始使用 Node.js 和 Koa 创建 API。我正在使用 Mocha/Chai 进行测试,但由于某种原因,我的任何try/catch
块都没有测试catch
块。例如,这里是 Coveralls.io 的输出:
router.get(BASE_URL, async (ctx) => {
try {
const companies = await queries.getAllCompanies();
ctx.body = {
status: 'success',
data: companies
};
} catch (err) {
ctx.status = 400; // !
ctx.body = { // !
status: 'error',
message: err.message || 'Sorry, an error has occurred.'
};
}
}
分支 [[0, 0], [0, 1]] 丢失。
我已经用// !
代码中提到的两行标记了。这是我的test.js
文件中测试GET
API 的相关部分:
describe('GET /api/v1/companies', () => {
const companies = realm.objects('Company');
it('should return an empty list', (done) => {
chai.request(server)
.get('/api/v1/companies')
.end((err, res) => {
should.not.exist(err);
res.status.should.equal(200);
res.type.should.equal('application/json');
res.body.status.should.eql('success');
Object.keys(res.body.data).length.should.eql(0);
done();
});
});
it('count should be 0', (done) => {
companies.length.should.eql(0);
done();
});
it('should return 3 newly added companies', (done) => {
realm.write(() => {
realm.create('Company', { id: '1', companyName: 'test company 1' });
realm.create('Company', { id: '2', companyName: 'test company 2' });
realm.create('Company', { id: '3', companyName: 'test company 3' });
});
chai.request(server)
.get('/api/v1/companies')
.end((err, res) => {
should.not.exist(err);
res.status.should.equal(200);
res.type.should.equal('application/json');
res.body.status.should.eql('success');
Object.keys(res.body.data).length.should.eql(3);
res.body.data[0].should.include.keys('id', 'companyName', 'notes', 'notesSalt');
done();
});
});
it('count should be 3', (done) => {
companies.length.should.eql(3);
done();
});
});
我需要做些什么来增加catch
区块的覆盖范围?我对多个 API 有同样的问题,所以我肯定想纠正测试。
解决方案
实际上,“await”语句是 try-catch 块中“promise”的包装。因此,“await”部分中发生的任何错误实际上都发生在包装器 try-catch 块中。所以你不能像这样捕捉这些错误。
但是你会得到这样的错误,
await queries.getAllCompanies().catch((err) => { ... })
推荐阅读
- android - 如何在工作管理器中管理 2 个不同的 android 定期任务
- cordova - 离子 Java 插件禁用硬件后退按钮
- .net - Powershell 中的 ToWorkBook 错误
- sockets - 使用 BR-POP 和 Socket 时出现阻塞线程异常
- java - 使用 explorer.exe 获取文件夹名称和路径作为 java 程序中的输入
- cmake - 为什么 CMake / include_external_msproject 不传播平台参数?
- jquery - 获取动态创建的下拉列表的值
- c# - 如何使用 RGB 值通过黄色从红色渐变到绿色?
- android - Ionic 3 存储容量
- swift - 十六进制到二进制代码错误?