Я использую chai-as-promised
для проверки моей readIndex(path): string
функции.
readIndex () возвращает обещание, которое, в свою очередь, пытается открыть и проанализировать JSON файл с именем index.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
параметр по умолчанию?