【发布时间】:2022-02-10 22:59:27
【问题描述】:
我正在使用chai-as-promised 来测试我的readIndex(path): string 功能。
readIndex() 返回一个 promise,然后尝试打开目标文件夹中名为 index.json 的文件并将其解析为 JSON。
请参阅以下摘录:
// readIndex.js
module.exports = path =>
new Promise((resolve, reject) => {
try {
const buffer = fs.readFileSync(path + '/index.json')
const data = JSON.parse(buffer.toString())
resolve(data)
} catch (err) {
if (err.code === 'ENOENT') {
reject(Error('file not found'))
} else if (err instanceof SyntaxError) {
reject(Error('format not json'))
} else {
reject(err)
}
}
})
在我的案例测试的模拟中,返回的承诺拒绝并出现错误“找不到文件”。
但实际上我正在测试一个(应该是)有效的案例,只有在承诺成功解决的情况下才应该通过 ...
至少这是我对promise.should.be.fulfilled 用法的理解。
查看相关测试:
// readIndex.test.js
chai.use(chaiAsPromised)
chai.should()
describe('SUCCESS :', () =>
it('should resolve with a (markdown) string extrapoled from target folder index file', done => {
const key = 'content success'
mock(_mocks[key])
const promise = readIndex('test')
promise.should.be.fulfilled
mock.restore()
done()
}))
通过这样的设置,运行测试不会使其失败;它会打印此消息:
SUCCESS :
√ should resolve with a (markdown) string extrapoled from target folder index file
(node:183516) UnhandledPromiseRejectionWarning: AssertionError: expected promise to be fulfilled but it was rejected with 'Error: file not found'
(node:183516) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 10)
(node:183516) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
当然,预期的结果应该是失败的测试运行,在控制台中是这样的:
SUCCESS :
1) should resolve with a (markdown) string extrapoled from target folder index file:
AssertionError: expected '1' to equal '2'
这种奇怪的行为甚至会导致(有趣和)不连贯的警告。
使用promise.should.not.be.rejected,我得到“预期不会被拒绝但被拒绝的承诺”但测试仍然通过:
SUCCESS :
√ should resolve with a (markdown) string extrapoled from target folder index file
(node:225676) UnhandledPromiseRejectionWarning: AssertionError: expected promise not to be rejected but it was rejected with 'Error: file not found'
其实我的想法是:
一种解决方案是将测试失败的级别提高到警告,但我在
chai-as-promised文档中没有找到它。另一种解决方案是了解哪个层正在捕获错误/拒绝,并将其降低为警告。也许是
chai-as-promised默认参数?
【问题讨论】:
-
假设你需要一个 Promise,在某些情况下你的 Promise 既不会解决也不会拒绝。
if (err.code === 'ENOENT') {...}需要else {reject(err)}。 -
是的,你是对的。它在我的代码中,但我只是缩短了要发布的代码,抱歉
-
你会注意到我还在输入这个
if (err.code === 'ENOENT'),因为第一行的警告证明了这一点 -
只是想我会提到它,以防不履行承诺可能是一个促成因素。
标签: javascript node.js promise chai