当用作对象属性时,Spy返回callcount 0

问题描述 投票:1回答:1

我正在尝试编写测试,检查是否已调用第三方库函数。

测试:(摩卡)

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 sinon
1个回答
0
投票

Promise解析时,回调在PromiseJobs queue中排队,在当前运行的消息完成后进行处理。

在这种情况下,您的函数在PromiseJobs中排队回调,当前运行的消息是测试本身,因此测试运行完成,然后在PromiseJobs中排队的作业才有机会运行。

因为PromiseJobs中的作业还没有运行,所以当它进入channelSpy测试时测试失败,因为它还没有被调用。


Promise返回的init已被链接到由Promisesconnect返回的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
});
© www.soinside.com 2019 - 2024. All rights reserved.