我了解您无法兑现承诺,因此无法在摩卡测试中使用done
。我什么都没退,只是打电话给完成。但是我仍然会收到错误消息。
节点12.4.0 摩卡5.2.0
NPM测试脚本:
"test": "mocha --timeout 10000 --compilers js:@babel/register test/utils.js"
摩卡测试:
const fs = require('fs');
const UTILS = require('../util');
describe('Utils', () => {
it('should delete a file that exists', async done => {
fs.writeFile('delete_me.txt', 'I will be deleted', async err => {
const result = await UTILS.deleteImgFiles(['delete_me.txt'], 10);
console.log('result', result);
if (result[0]) {
done();
} else {
done(new Error('test failed');
}
});
});
});
使用功能:
const fs = require('fs');
const utils = {
deleteImgFiles: (paths, time = 300000) => Promise.all(
paths.map(p => new Promise(
(resolve, reject) => {
if (!p) resolve(true);
try {
setTimeout(() => {
fs.unlink(p, err => {
if (err) {
reject(err);
} else {
console.log(`Deleted file ${p}`);
resolve(true);
}
})
}, time);
} catch (e) {
console.error(e);
}
}
)
))
}
module.exports = utils;
我希望该测试通过,但会引发错误。我想念什么?