【问题标题】:get the arguments with which a spy was called获取调用间谍的参数
【发布时间】:2021-04-05 05:12:36
【问题描述】:

我正在监视 EventEmitterAngular 中的方法 emit

spyOn(answerComponent.answerEmitter, 'emit');

我想检查 emit 是否使用参数 A 调用,但我不想检查与 A 的完全匹配。我想检查 emit 是否使用值 A.a, A.b 调用并忽略 A.c 的值。

有可能吗?

【问题讨论】:

    标签: jasmine angular6 angular-test


    【解决方案1】:

    我想到了两种方法:

    一个使用原生的toHaveBeenCalledWith

    expect(answerComponent.answerEmitter, 'emit').toHaveBeenCalledWith(A.a);
    expect(answerComponent.answerEmitter, 'emit').toHaveBeenCalledWith(A.b);
    // you can think of all the callers being tracked as an array and you can assert with
    // toHaveBeenCalledWith to check the array of all of the calls and see the arguments
    expect(anserComponent.anserEmitter, 'emit').not.toHaveBeenCalledWith(A.c); // maybe you're looking for this as well
    

    您还可以监视发射并调用假函数:

    spyOn(answerComponent.answerEmitter, 'emit').and.callFake((arg: any) => {
      // every time emit is called, this fake function is called
      if (arg !== A.a || arg !== A.b) {
         throw 'Wrong argument passed!!'; // you can refine this call fake
      }  // but the point is that you can have a handle on the argument passed and assert it
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-30
      • 2017-02-22
      • 2020-07-21
      • 2015-08-29
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多