【问题标题】:Spy returns callcount 0 when used as object property当用作对象属性时,Spy 返回 callcount 0
【发布时间】: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


    【解决方案1】:

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

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

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


    init 返回的Promise 已经链接到connectcreateChannel 返回的Promises,所以你所要做的就是让你的测试函数async 然后调用await on init返回的Promise

    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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-18
      • 2014-03-15
      • 1970-01-01
      • 2018-06-17
      • 2021-08-22
      • 2022-01-23
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多