首页 > 解决方案 > 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文件中测试GETAPI 的相关部分:

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 有同样的问题,所以我肯定想纠正测试。

标签: javascriptmocha.jschai

解决方案


实际上,“await”语句是 try-catch 块中“promise”的包装。因此,“await”部分中发生的任何错误实际上都发生在包装器 try-catch 块中。所以你不能像这样捕捉这些错误。

但是你会得到这样的错误,

await queries.getAllCompanies().catch((err) => { ... })

推荐阅读