【问题标题】:Expected =1, received=0 - why is my function not called in Angular test?预期 = 1,接收 = 0 - 为什么我的函数没有在 Angular 测试中调用?
【发布时间】:2020-11-24 06:44:10
【问题描述】:

我检查控制台 .. shownCategories 不是空的,但在测试中是空的

it("in case edit should call filterCategories()", () => {
         component.state == 'edit';
         if (component.state == 'edit') {
           const filterCategoriesSpy = spyOn(component, 'filterCategories').and.returnValue(
             [{
               hiddenVariants: 0,
               id: 187910,
               lang: "de",
               name: "AMG/Exterieur",
               plId: 5389,
               refId: "1015001000",
               type: "AMG",
               visibleVariants: 5
             }, {
               hiddenVariants: 0,
               id: 187911,
               lang: "de",
               name: "AMG/Interieur",
               plId: 5389,
               refId: "1015002000",
               type: "AMG",
               visibleVariants: 7,
             }]);
           expect(filterCategoriesSpy).toHaveBeenCalledTimes(1);
         }
       });
     }}

这是函数:

  public addFirstTable() {
    console.log("addFirstTable");
    //awel mara showncategories gaya fadya a lazm amlaha lw state msh edit
    if (this.state != "compare") {
      // this.shownCategories = this.allCategories.map(a => ({ ...a }));
      this.shownCatgeories = this.FilterShownCategories();
      console.log("shownCategories if state is not compare", this.shownCategories);
    }
}

输出:

expected=1, received=0

【问题讨论】:

    标签: angular unit-testing jasmine jestjs


    【解决方案1】:

    我想你忘了从测试中执行函数。

    添加下一行

    component.addFirstTable();
    

    在此之前

    expect(filterCategoriesSpy).toHaveBeenCalledTimes(1);
    

    【讨论】:

    • 我们应该添加这一行:var shownCategories = component.FilterShownCategories();expect(shownCategories).not.toEqual([]);
    • 如果解决了您的问题,请接受我的回答并点赞。
    • 你应该检查.toEqual(...),而不是.toEqual(...) returnValue 中的给定数组。
    • 如果我的回答对您有帮助,请接受我的回答。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2021-04-15
    • 2019-04-03
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多