获取调用间谍的参数

问题描述

我正在监视 emitEventEmitterAngular 方法

spyOn(answerComponent.answerEmitter,'emit');

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

可以吗?

解决方法

我想到了两种方法:

使用原生 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
});