【发布时间】:2021-04-23 11:24:07
【问题描述】:
我的组件中有这段代码。我尝试根据 id 获取类别的详细信息。我从一开始就已经有了 id,所以我只需要找到它的其余细节。
export class editCategoryComponent implements onInit {
const id='ABC'
let name='';
let category: Category[]=[];
constructor(catService: CategoryService)
ngOnInit(): void {
// code to get category, done
this.catService.getCategory().subscribe((data) => {
this.category = data;
});
// code to get detail of certain category
for(let i=0; i<this.category.length; i++) {
if(id === this.category[i].category_id) {
name=category[i].name;
break
}
}
}
}
我的单元测试是这样的。我在组件中设置了 id,并从我创建的模拟中设置了类别。它只是一个类别对象的数组。
mockCategory = [
{
category_id: 'ABC',
category_name: 'lorem ipsum'
},
{
category_id: '123',
category_name: 'lorem-ipsum'
},
]
describe('editCategoryComponent', () => {
let component: editCategoryComponent
let fixture: ComponentFixture<EditComponent>
let service: CategoryService
beforeEach(() => {
fixture = TestBed.createComponent(EditCategoryComponent)
component = fixture.componentInstance
service = fixture.debugElement.injector.get(CategoryService)
})
it('should get detail category and success', () => {
spyOn(service, 'getCategory).and.returnValue(of(mockCategory));
fixture.detechChanges();
component.id = 'ABC';
component.category.forEach((key), => {
if(key.category_id === component.id) {
fixture.detectChanges();
expect(component.name).toEqual(key.category_name);
}
})
})
}
到foreach为止,我的测试已经检测到component.category不为空,我认为它应该能够从中获取数据。但是我得到一个错误 expect(received).toEqual(expected) // 深度相等。它说预期:“文本”,接收:“”,我也在寻找覆盖范围,它只覆盖 if 语句。语句去“name=...”等等不包括在内。那么如何让单元测试覆盖在 if 语句之后呢?
我已经让组件中的id存在于category中,所以应该继续if。我在这里做错了吗?
谢谢!
【问题讨论】:
-
请提供组件的完整代码
-
我已经提供了完整的组件代码
-
@vjchrisintha 不确定这部分在做什么,// 获取类别的代码,完成 您正在从注入器获得一些未使用的服务。您确定它不会在某处初始化类别数组。附言你不需要为每个类别运行detectChanges。尝试将其移至 foreach 上方。我会留下答案,因为它部分有用。
-
实际上我在单元测试中使用spy做了类别,所以我spy了(mockCategory)的服务和返回值。我认为这并不重要,因为我在控制台上检查了它并且我的数组已满。那我改一下。
标签: angular typescript unit-testing angular-test