【发布时间】:2021-04-10 02:23:22
【问题描述】:
我有一个具有以下类的 NodeJS + Typescript 应用程序:
export default class OrderStreamWriter {
private readonly redis: IORedis;
private readonly orderStream: string;
private readonly logger: LoggerFactory;
constructor(redisHost: string, redisPort: number, redisPass: string, orderStream: string) {
this.orderStream = orderStream;
this.redis = createRedisClient(redisHost, redisPort, redisPass);
this.logger = new LoggerFactory('streams/OrderStreamWriter');
}
public async write(msg: string): Promise<void> {
await this.redis.xadd(this.orderStream, '*', 'trade', msg).catch((err: Error) => {
this.logger.log(
`Error Writing message to stream (${this.orderStream}): ${err.message}. Quitting...`,
);
process.exit(1);
});
}
}
在另一个类中,我使用write 方法将结果写入Redis 流。
我想在不调用实际的 write 函数的情况下测试该流程,而只是检查该函数是否会使用某些参数被调用,这是我的测试(使用 mocha + sinon 运行):
it('process the input and return an order', () => {
const rule = directOrder[0].rule;
const user = directOrder[0].user;
//const writeStub = sinon.stub(OrderStreamWriter.prototype, "write");
const Writer: any = sinon.stub();
sinon.stub(Writer.prototype, "write");
const writer = new Writer();
const order = {}
// console.log(writeStub)
const directTriggerStrategy: TriggerContext = new TriggerContext(user, rule, writer);
directTriggerStrategy.execute()
sinon.assert.calledWithExactly(writer, order);
})
使用当前代码和注释行 const writeStub = sinon.stub(OrderStreamWriter.prototype, "write"); 我在运行测试时收到相同的错误:
TypeError: Cannot stub non-existent property write
我该如何解决这个问题?
【问题讨论】:
-
请提供您要测试的
TriggerContext类的代码。 -
您确定您导入到测试文件并调用
ObjectStreamWriter的对象是正确的对象吗?我注意到该类是其文件中的 default 导出。至于带有注释行的测试,您可以将Writer的定义更改为class Writer { write() {} }并且给定的错误应该消失
标签: javascript mocha.js sinon