【问题标题】:Unit testing a method in Angular with Karma/Jasmin使用 Karma/Jasmine 对 Angular 中的方法进行单元测试
【发布时间】:2020-07-11 19:41:14
【问题描述】:

我必须使用 Jasmine/Karma 在 Angular 中测试一个方法,但我总是收到错误消息:

TypeError: undefined is not iterable (cannot read property Symbol (Symbol.iterator))

我构造了这样的方法:

  myMethod(locs: MyCustomType1[], clocs: MyCustomType2[]) {
    clocs = clocs
      .filter(cl => cl !== null && cl.l_ids !== null);
    locs = locs
      .filter(l => l !== null && l.id !== null);

    clocs.forEach(
      cl => {
        cl['l_names'] = [];
        locs.forEach(
          l => {
            if (cl.l_ids.includes(l.id)) {
              clocs['l_names'].push(l.name);
            }
          }
        );
      }
    );
  }

我的测试目前看起来像这样:

  describe('#MyMethod', () => {
    beforeEach(() => {
      component.clocs = mockClocs;
      component.locs = mockLocs;
      component.myMethod(mockLocs, mockClocs);
    });
    describe('#myMethod)', () => {
      it('The clocs and locs array should by defined', () => {
        expect(component.clocs).toBeDefined();
        expect(component.locs).toBeDefined();
      });

      it('The clocs array should include "Location2" and "Location3" with the locationIds 2, 3', () => {
        expect(component.clocs[1]['l_names'].includes('Location2')).toBeTruthy();
        expect(component.clocs[1]['l_names'].includes('Location3')).toBeTruthy();
      });
    });
  });

我的 it() 语句中的每个 expect() 方法都会抛出上述错误消息。如果我记录数组,我可以看到它们是用所需的值定义的,但 expect() 方法返回未定义。嗯

我做错了什么?

【问题讨论】:

  • 分享错误截图。行号是多少
  • 我的 it() 语句中的每个 expect() 方法都会抛出上述错误消息。如果我记录数组,我可以看到它们是用所需的值定义的。 expect() 方法返回未定义。嗯
  • 为什么你有嵌套describe 同名describe('#myMethod)', () => { 你能把它也删除吗?也请分享更多代码。似乎这些值没有按照您执行它的顺序设置。

标签: angular typescript unit-testing jasmine karma-jasmine


【解决方案1】:

你可以使用 .toEqual()

      it('The clocs array should include "Location2" and "Location3" with the locationIds 2, 3', () => {
        expect(component.clocs).toEqual([{l_names: ['Location2', 'Location3']}]);
      });

【讨论】:

    【解决方案2】:

    我不得不在 beforeEach 方法中调用 ngOnChanges(),因为我的数组是在这个生命周期方法中填充的。所以我这样解决了:

      beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        component.clocs = mockClocs;
        component.locs = mockLocs;
        component.myMethod(mockLocs, mockClocs);
        component.ngOnChanges();
        fixture.detectChanges();
      });
    

    我还删除了不需要的描述块。

    希望这个答案有帮助。如果您有任何改进建议,请告诉我:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多