间谍如何在Angular 7中使用Jasmine?

时间:2019-01-24 11:32:04

标签: jasmine angular6 karma-jasmine karma-runner angular7

我已经使用spyOn创建了这个间谍

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

在Adder类中,我具有以下功能

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

}

quoteList数组的长度为2

我得到的结果

  

错误:: add()方法不存在

2 个答案:

答案 0 :(得分:1)

我认为您不能像这样直接监视类Adders的功能,而是监视prototype或创建该类的实例并对其进行监视。我将使用两个间谍并像这样实现它:

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块中使用类的实例,您可以这样定义实例:

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

答案 1 :(得分:0)

借助Fabian答案,我能够调试并解决问题。实际上,我需要在要监视的类内触发该函数。这样做之后,它给了我预期的输出。

测试用例

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

要监视的类中的功能

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