我正在使用 chai-as-promised
来测试我的 readIndex(path): string
函数。
readIndex() 返回一个 Promise,该 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 拒绝并出现错误“找不到文件”。
但实际上我正在使用(应该是)有效的案例进行测试,只有在 promise 成功解决时才应通过 ...
至少这是我对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
,我得到“预期 promise 不会被拒绝,但它被拒绝”,但测试仍然通过:
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
默认参数?
最佳答案
我刚刚在 chai-as-promised
documentation中发现了这个小事实。 :
测试“行”(我没有更好的词)前面必须有return
声明。
让我们看一下他们的第一个示例:
return doSomethingAsync().should.eventually.equal("foo")
下面的内容也很有趣:
or if you have a case where return is not preferable (e.g. style considerations) or not possible (e.g. the testing framework doesn’t allow returning promises to signal asynchronous test completion), then you can use the following workaround (where done() is supplied by the test framework):
doSomethingAsync().should.eventually.equal("foo").notify(done);
它对我有用。
希望它能帮助人们。
关于javascript - chai-as-promised 拒绝不会导致测试失败,但只会打印警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56669385/