给定以下 NodeJS 转换流:
class ObjectToCSVTransform extends Transform {
private hasSetHeaders: boolean;
constructor() {
super({ objectMode: true });
this.hasSetHeaders = false;
}
static create(): ObjectToCSVTransform {
return new this();
}
_write(
object: Record<string, unkwnown>,
_encoding: BufferEncoding,
callback: TransformCallback
): void {
this.push(this.generateCSV(telemetry));
callback();
}
private generateCSV(object: Record<string, unkwnown>): string {
let csv = '';
if (!this.hasSetHeaders) {
csv += this.createCSVHeaders(object);
this.hasSetHeaders = true;
}
csv += this.createRecord(object);
return csv;
}
private createCSVHeaders(object: Record<string, unkwnown>): string {
return `${Object.keys(object)}\n`;
}
private createCSVRecord(object: Record<string, unkwnown>): string {
return `${Object.values(object)}\n`;
}
}
我实现了以下测试用例(使用jest),以测试给定“相同类型”的普通对象流的预期输出是否为有效的 CSV他们的代表:
describe('object to csv stream', () => {
const items: Record<string, unknown> = [
{ foo: 1, bar: 2, baz: 3 },
{ foo: 10, bar: 20, baz: 30 },
{ foo: 100, bar: 200, baz: 300 },
];
it('should transform a list of items to csv', (done) => {
const expectedCsv = 'foo,bar,baz\n1,2,3\n10,20,30\n100,200,300\n';
let csv = '';
Readable.from(items)
.pipe(ObjectToCSVTransform.create())
.on('data', (csvResult) => {
csv += csvResult;
console.log(csvResult); // just for debugging purposes
})
.on('end', () => {
console.log('streaming ended'); // just for debugging purposes
expect(csv).toEqual(expectedCsv);
done();
});
});
});
显然,在测试用例实现期间,我想看看我的测试用例是如何失败的:流似乎可以正常工作,因为它记录了每个预期的 csv 结果行和“流结束”<一旦流结束,
消息也会出现在末尾,但测试执行根本没有完成。开 Jest ,超过默认超时后居然执行完了:
thrown: "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
我在这里缺少什么?
请注意,我当前正在使用 jest 回调来通知异步操作何时完成。
最佳答案
我的测试用例中遗漏了一些东西,它根本没有正确处理异步,因此导致 jest 抛出超出超时异常
:
- 用 try-catch 包围断言,并在断言失败时调用
done()
回调。
.on('end', () => {
try {
expect(csv).toEqual(expectedCsv);
done();
} catch (error) {
done(error);
}
});
有关更多信息/引用,请查看 Jest 文档:https://jestjs.io/docs/asynchronous#callbacks
关于javascript - 使用 jest 对 NodeJS 流进行单元测试 - 超时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70992048/