【问题标题】:Jasmine Testing ForEach and getting cannot read property ''forEach''Jasmine 测试 ForEach 并获取无法读取属性“forEach”
【发布时间】:2020-01-22 19:16:02
【问题描述】:

我正在测试一种将属性推送到我的数组的方法...但出现错误:无法读取未定义的属性“forEach”。

我该如何解决这个问题?

注意:我基本上是在测试一种在 mu HTML 上使用 mat-autocomplete 的方法,因此 forEach 为自动完成提供数据

规格

mockCustomer = [{
      'id': "45831a77-5fee-49f0-8c87-3de1e881fcd1",
      'name': "John Doe",
      'alias': "John",
      'isEnabled': true,
      'updatedOn': "12-12-2020",
      'updateBy': "Daniel"
    },
    {
      'id': "c5c90f2e-b712-43a0-bf8d-0fdfe9c07076",
      'name': "Jeff Doe",
      'alias': "Jeff",
      'isEnabled': true,
      'updatedOn': "10-12-2020",
      'updateBy': "Daniel"
    }]

it('should push on Customer', () =>{
    const spy = spyOn(component, 'pushOnCustomerNames').and.callThrough();
    component.pushOnCustomerNames();

    mockCustomer.forEach(element =>  {
      mockCustomer.push(element.name)
    });

    expect(spy).toHaveBeenCalled();

  })

组件

pushOnCustomerNames() {
    this.customerNames = [];
    this.customer.forEach((customer: CustomersViewModel) => {
      this.customerNames.push(customer.name);
    });
  }

getCustomers() {
    this._managService.getCustomers().then(customerResponse => {
      this.customer = customerResponse;
      this.pushOnCustomerNames();
      this.filterCustomers();
    }).catch((err) => {
      this.toastr.error(err);
    })
  }

filterCustomers() {
    this.filteredCustomer = this.formFilter.get("customerName").valueChanges
      .pipe(
        startWith(''),
        map(value => this._filterCustomer(value))
      );
  }

_filterCustomer(value: string): string[] {
    return this.customerNames.filter(customer => customer.includes(value));
  }

【问题讨论】:

    标签: angular testing jasmine


    【解决方案1】:

    你在哪里定义 mockCustomer ???我不明白。如果不定义,就不能在 undefined 上使用 forEach

    编辑:

    看看我试图重现你的错误:

    enter image description here

    我有同样的错误:

    问题是因为我在afterEach中将值放在mockCustomer中,您需要将vmockCustomer值放在beforeEach中,如下所示:

    我在控制台 mockCustomer 值中显示。

    【讨论】:

    • 我没有发现任何问题。也许你在 afterEach 中初始化 mockCustomer?
    • 它看起来像我以前的代码,但仍然无法正常工作
    • 你能添加所有spec.ts的照片吗?
    猜你喜欢
    • 2018-05-13
    • 2017-10-10
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多