【发布时间】:2019-03-13 16:15:28
【问题描述】:
我正在尝试编写检查第三方库函数是否已被调用的测试。
测试:(摩卡)
describe('SomeClassTest', () => {
describe('Setup', () => {
beforeEach(() => {
const channel = {createChannel: () => 'channel created'};
// @ts-ignore
this.channelSpy = Sinon.spy(channel, 'createChannel');
// @ts-ignore
Sinon.stub(amqplib, 'connect').returns(channel);
});
// @ts-ignore
afterEach(() => amqplib.connect.restore());
it('Should check if SomeClass has created Channel', () => {
const someclass = SomeClass.getInstance();
someclass.init();
// @ts-ignore
expect(amqplib.connect.callCount).to.be.eq(1); // True
// @ts-ignore
expect(this.channelSpy.callCount).to.be.eq(1); // False :(
});
});
});
班级:
export default class SomeClass {
private connection?: amqplib.Connection;
public async init() {
await this.connect();
await this.createChannel();
}
private async connect(): Promise<void> {
this.connection = await amqplib.connect(this.connectionOptions);
}
private async createChannel(): Promise<void> {
if (!this.connection) {
throw new Error('Some Error :)');
}
this.channel = await this.connection.createChannel();
}
}
我确定 this.connection.createChannel() 已被调用,但测试不想证明这一点,有人可以帮助我可怜的灵魂吗?:)
【问题讨论】:
标签: typescript unit-testing mocha.js sinon