Angular 用Karma/Jasmin对一种方法进行单元测试
我必须用Jasmine/Karma测试一种方法,但我总是得到错误信息: TypeError:undefined不可修改(无法读取属性符号 (符号迭代器) 我构建了如下方法:Angular 用Karma/Jasmin对一种方法进行单元测试,angular,typescript,unit-testing,jasmine,karma-jasmine,Angular,Typescript,Unit Testing,Jasmine,Karma Jasmine,我必须用Jasmine/Karma测试一种方法,但我总是得到错误信息: TypeError:undefined不可修改(无法读取属性符号 (符号迭代器) 我构建了如下方法: myMethod(locs: MyCustomType1[], clocs: MyCustomType2[]) { clocs = clocs .filter(cl => cl !== null && cl.l_ids !== null); locs = locs
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();
});
});
});
我的测试目前如下所示:
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()方法返回undefined。嗯 我做错了什么?您可以使用.toEqual() 我必须在beforeach方法中调用ngOnChanges(),因为我的数组是在这个生命周期方法中填充的。所以我是这样解决的:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.clocs = mockClocs;
component.locs = mockLocs;
component.myMethod(mockLocs, mockClocs);
component.ngOnChanges();
fixture.detectChanges();
});
我还删除了不需要的描述块
希望这个答案有帮助。如果您有任何改进建议,请告诉我:)分享错误截图。对于我的it()语句中的每个expect()方法,都会抛出上述错误消息的行号。如果我记录数组,我可以看到它们是用所需的值定义的。expect()方法返回undefined。嗯,为什么您有同名的
descripe
,()=>{嵌套,请您也删除它。另外,请共享更多代码。似乎值没有按照您执行它的顺序设置。