[英]How to test a “throwing an error” in Mocha having it in asyncronous code (read from db) using only callbacks (no promises, async/await)?
I want to write some tests for a method which reads from a JSON file (simulating a db) and returns the correct name, given that exists. 我想为从JSON文件(模拟数据库)读取的方法编写一些测试,并返回正确的名称(如果存在)。
This is the code I have written for my method. 这是我为我的方法编写的代码。 It does throw an error when the id is not valid.
当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);
});
...
The test I have written is: 我写的测试是:
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();
}
But it doesn't seem to pass the test. 但它似乎没有通过测试。 When I have the 'done()' uncommented, it passes the test, but I don't think it is because I pass the actual test, but rather because the test gets in the catch and executes the done() callback.
当我对'done()'取消注释时,它会通过测试,但我不认为这是因为我通过了实际测试,而是因为测试进入了catch并执行了done()回调。
Any help, guidance or recommendation is much appreciated. 任何帮助,指导或建议都非常感谢。
You won't be able to catch an Error
being thrown in the fs.readFile
callback. 您将无法捕获
fs.readFile
回调中抛出的Error
。
Instead, pass any errors to the callback you pass to getOne
. 相反,将任何错误传递给您传递给
getOne
的回调。
Then you can check if an Error
got passed to your callback in your test. 然后,您可以检查
Error
是否已在测试中传递给您的回调。
Here is a working example to get you started: 这是一个让您入门的工作示例:
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();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.