如何在仅使用回调(无承诺,async/await)的异步代码(从数据库读取)中测试 "throwing an error"?

How to test a "throwing an error" in Mocha having it in asyncronous code (read from db) using only callbacks (no promises, async/await)?

我想为从 JSON 文件(模拟数据库)和 returns 正确名称读取的方法编写一些测试,前提是它存在。

这是我为我的方法编写的代码。当 id 无效时它确实会抛出错误。

const getOne = (id, callback) => {
    ...
    fs.readFile('db.json', (err, data) => {
      if (err) {
        throw new Error('Error reading file');
      }
      const person = JSON.parse(data)
        .filter(el => el.id === id)
        .map(el => el.name);
      if (person.length === 0) {
        throw new Error('It does not match DB entry');
      }
      callback(person);
    });
    ...

我写的测试是:

it('Should reject an invalid id', (done) => {

    api.getOne(100, (person) => {
      try {
        personFromDB = person;
      } catch (error) {

        assert.throws(() => {  
          }, new Error('It does not match DB entry'));
          //done();
      }

不过好像没过关。当我取消注释 'done()' 时,它通过了测试,但我不认为这是因为我通过了实际测试,而是因为测试进入了 catch 并执行了 done() 回调。

非常感谢任何帮助、指导或建议。

您将无法捕捉到 fs.readFile 回调中抛出的 Error

相反,将任何错误传递给您传递给 getOne 的回调。

然后您可以检查 Error 是否在您的测试中传递给您的回调。

这是一个可以帮助您入门的工作示例:

const fs = require('fs');
const assert = require('assert');

const api = {
  getOne: (id, callback) => {
    // ...
    fs.readFile('db.json', (err, data) => {
      if (err) return callback(err);  // <= pass err to your callback
      const person = JSON.parse(data)
        .filter(el => el.id === id)
        .map(el => el.name);
      if (person.length === 0) return callback(new Error('It does not match DB entry'));  // <= pass the Error to your callback
      callback(null, person);  // <= call the callback with person if everything worked
    })
  }
}

it('Should reject an invalid id', done => {
  api.getOne(100, (err, person) => {
    assert.strictEqual(err.message, 'It does not match DB entry');  // Success!
    done();
  });
});