使用Karma / Jasmin对Angular中的方法进行单元测试

时间:2020-03-31 09:35:27

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

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

TypeError:undefined不可迭代(无法读取属性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()方法返回的是未定义的。嗯

我在做什么错了?

2 个答案:

答案 0 :(得分:0)

您可以使用.toEqual()

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

答案 1 :(得分:0)

我必须在beforeEach方法中调用ngOnChanges(),因为我的数组已填充到此生命周期方法中。所以我这样解决了:

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

我还删除了不需要的describe块。

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