我正在尝试编写测试,检查是否已调用第三方库函数。
测试:(摩卡)
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()已被调用,但测试不想证明它,有人会帮助我的可怜的灵魂吗?:)
当Promise
解析时,回调在PromiseJobs queue中排队,在当前运行的消息完成后进行处理。
在这种情况下,您的函数在PromiseJobs中排队回调,当前运行的消息是测试本身,因此测试运行完成,然后在PromiseJobs中排队的作业才有机会运行。
因为PromiseJobs中的作业还没有运行,所以当它进入channelSpy
测试时测试失败,因为它还没有被调用。
由Promise
返回的init
已被链接到由Promises
和connect
返回的createChannel
所以你所要做的就是让你的测试函数async
然后在await
返回的Promise
上调用init
:
it('Should check if SomeClass has created Channel', async () => { // async test function
const someclass = SomeClass.getInstance();
await someclass.init(); // await the Promise returned by init
// @ts-ignore
expect(amqplib.connect.callCount).to.be.eq(1); // True
// @ts-ignore
expect(this.channelSpy.callCount).to.be.eq(1); // True
});