Angular 7 中的间谍如何与 Jasmine 合作?

How spy works with Jasmine in Angular 7?

我使用 spyOn 创建了这个间谍

it("spyon ", () => {
  const searchChangeEmitSpy =  spyOn(Adders.countlist,"add");
  expect(searchChangeEmitSpy.calls.count()).toEqual(2);
});

在 Adder 里面 class 我有以下函数

countlist(){ const i =0;
  this.quoteList.forEach(element => {
       console.log(element); 
       this.add(4,i++);    
  });

}

quoteList 数组的长度为 2

结果是什么

Error: : add() method does not exist

我认为您不能像这样直接监视 class Adders 的函数,而是监视 prototype 或创建 [=22] 的实例=] 并监视它。我会使用两个间谍并像这样实现它:

it("spyon", () => {
  const countlistSpy = spyOn(Adders.prototype, 'countlist');
  const addSpy = spyOn(Adders.prototype, 'add');

  // call your function / trigger something that calls the function

  expect(countlistSpy).toHaveBeenCalledTimes(1);
  // more expectations here
});

或者在 beforeEach 块中使用 class 的实例,您可以这样定义您的实例:

let adder: Adders = new Adders();

然后您的测试将如下所示:

it("spyon", () => {
  const countlistSpy = spyOn(adder, 'countlist');
  const addSpy = spyOn(adder, 'add');

  // call your function / trigger something that calls the function

  expect(countlistSpy).toHaveBeenCalledTimes(1);
  // more expectations here
});

在 Fabian 回答的帮助下,我能够调试并解决我的问题。实际上,我需要触发我正在监视的 class 中的函数。这样做之后,它给了我预期的输出。

测试用例

it("spyOn countList add()", () => {
          const searchChangeEmitSpy =  spyOn(Adders,"add");
          Adders.addNewQuote("This is my second post");
          Adders.countlist(0);
          expect(searchChangeEmitSpy.calls.count()).toEqual(2);
        });

class 内的函数被窥探

 countlist(i:number){
          this.quoteList.forEach(element => {
               console.log(element); 
               this.add(4,i++);    
          });
         //return i; 
      }