【问题标题】:How spy works with Jasmine in Angular 7?间谍如何在 Angular 7 中使用 Jasmine?
【发布时间】:2019-01-24 11:32:04
【问题描述】:

我使用 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() 方法不存在

【问题讨论】:

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


    【解决方案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
    });
    

    【讨论】:

    • 感谢您的回答,这不是我想要的,但这有助于我了解自己犯了什么错误以及间谍实际上是如何工作的。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2017-09-26
      • 2018-02-07
      相关资源
      最近更新 更多