【问题标题】:expect(spy).toHaveBeenCalledTimes(expected) Expected number of calls: 1 Received number of calls: 0expect(spy).toHaveBeenCalledTimes(expected) 预期通话次数:1 接听通话次数:0
【发布时间】:2020-11-19 05:10:24
【问题描述】:

第一次如果很简单,对不起这是我第一次写单元测试。我写我的代码来测试fn是否在条件下被调用一次

it("fill shownCategories when state not compare", () => {

  component.state != 'compare'
  if (component.state != 'compare') {

    const filterShownCategoriesSpy = spyOn(component, 'FilterShownCategories').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(filterShownCategoriesSpy).toHaveBeenCalledTimes(1);
    expect(component.shownCatgeories).toEqual([]);
  }
});

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

输出 期望(间谍).toHaveBeenCalledTimes(期望)

Expected number of calls: 1
Received number of calls: 0

【问题讨论】:

  • 请提供可以重现问题的stackoverflow.com/help/mcve。不清楚你发的sn-p和测试有什么关系,也不清楚component.state != 'compare' if (component.state != 'compare') {在测试中的目的是什么。测试失败是因为在spyOnexpect(filterShownCategoriesSpy) 之间应该有调用filterShownCategories 的代码才能通过测试,而目前没有,肯定没有调用。

标签: angular unit-testing jestjs


【解决方案1】:

首先,你给状态赋值是错误的。

改变这个

 component.state != 'compare';

 component.state = 'any state';

并添加以下行

component.addFirstTable();

之前

expect(filterCategoriesSpy).toHaveBeenCalledTimes(1);

【讨论】:

  • 如果可行,请也接受此答案。谢谢。
猜你喜欢
  • 2020-09-15
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2023-03-12
  • 2012-03-24
相关资源
最近更新 更多