代码之家  ›  专栏  ›  技术社区  ›  Sayed Mohd Ali

间谍如何与茉莉花在角度7?

  •  0
  • Sayed Mohd Ali  · 技术社区  · 6 年前

    我用间谍创造了这个间谍

    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 回复  |  直到 6 年前
        1
  •  1
  •   Fabian Küng    6 年前

    我认为你不能直接监视这个班的功能 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
  •  0
  •   Sayed Mohd Ali    6 年前

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