在编写涉及“createReadStream”和“readline.createInterface”的代码单元测试时,我遇到了这个问题。
下面是我需要测试的代码:
private createReadStreamSafe(filePath: string): Promise<fs.ReadStream> {
return new Promise((resolve, reject) => {
const fileStream = fs.createReadStream(filePath)
console.log('file Stream')
fileStream
.on('error', () => {
reject('create read stream error')
})
.on('open', () => {
resolve(fileStream)
})
})
}
async start() {
const fileStream = await this.createReadStreamSafe(this.filePath)
const rl = readline.createInterface({
input: fileStream,
output: process.stdout,
terminal: false
})
for await (const line of rl) {
...
}
}
下面是我的测试,
it.only('should create an error if creating the read stream from the file path fails', () => {
const mockedReadStream = new Readable()
jest.spyOn(fs, 'createReadStream').mockReturnValue(mockedReadStream as any)
const app = createApp('invalid/file/path')
expect.assertions(1)
try {
app.start()
mockedReadStream.emit('error', 'Invalid file path')
} catch (error) {
expect(getErrorMessage(error)).toBe('Invalid file path')
}
})
但是,我知道了:
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: 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(). The promise rejected with the reason "undefined".] {
code: 'ERR_UNHANDLED_REJECTION'
}
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
发布于 2021-12-19 00:56:33
模拟的结果是被拒绝的承诺,这是无法处理的。测试应该是异步的,并返回一个承诺,即be async
。try..catch
不能在同步函数中处理它。
由于承诺在调用mockedReadStream.emit时被拒绝,因此在承诺被拒绝后不久就需要用catch链接起来,例如通过Jest承诺断言:
let promise = app.start()
mockedReadStream.emit('error', 'Invalid file path')
await expect(promise).rejects.toThrow('Invalid file path')
这暴露了测试单元中的问题,因为reject()
没有传递错误。
https://stackoverflow.com/questions/70409660
复制相似问题