[英]Unit testing a method in Angular with Karma/Jasmin
I have to test a method in Angular with Jasmine/Karma, but I always get the error message:我必须使用 Jasmine/Karma 在 Angular 中测试一个方法,但我总是收到错误消息:
TypeError: undefined is not iterable (cannot read property Symbol (Symbol.iterator))
TypeError: undefined is not iterable (cannot read property Symbol (Symbol.iterator))
I constructed the method like this:我构造了这样的方法:
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);
}
}
);
}
);
}
My test currently looks like this:我的测试目前看起来像这样:
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();
});
});
});
The mentioned error message gets thrown for every expect() method in my it() statement.我的 it() 语句中的每个 expect() 方法都会抛出提到的错误消息。 If I log the array I can see that they are defined with the needed values but the expect() method returns undefined.
如果我记录数组,我可以看到它们是用所需的值定义的,但 expect() 方法返回未定义。 Hmm
唔
What am I doing wrong?我究竟做错了什么?
You can use .toEqual()您可以使用 .toEqual()
it('The clocs array should include "Location2" and "Location3" with the locationIds 2, 3', () => {
expect(component.clocs).toEqual([{l_names: ['Location2', 'Location3']}]);
});
I had to call ngOnChanges() within the beforeEach method since my arrays are filled within this lifecycle method.我不得不在 beforeEach 方法中调用 ngOnChanges(),因为我的数组是在这个生命周期方法中填充的。 So I solved it like this:
所以我是这样解决的:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.clocs = mockClocs;
component.locs = mockLocs;
component.myMethod(mockLocs, mockClocs);
component.ngOnChanges();
fixture.detectChanges();
});
I also removed the unneeded describe block.我还删除了不需要的 describe 块。
Hope this answer helps.希望这个答案有帮助。 If you have any suggestions for improvements let me know :)
如果您有任何改进建议,请告诉我:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.