【问题标题】:Make a Unit Test in for-if statement Angular在 for-if 语句 Angular 中进行单元测试
【发布时间】: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


【解决方案1】:

您希望在 detectchanges() 之后运行的那段代码可能没有被执行。 所以在你没有给我们完整的代码之后,我假设你可能使用了一些 钩子,ngOnChanges 或 ngOnInit。 这里有两种可能的情况。

  1. 您正在使用 ngOnInit
  • 要调用 ngOnInit,您需要使用 TestBed.createComponent()
  • 您可以手动调用该函数component.ngOnInit()
  1. 您正在使用 ngOnChange
  • 您可以手动调用 ngOnChange
  • 您可以将您的组件包装在一个新的测试组件中并在那里测试结果。 Check this article

【讨论】:

  • 我已经提供了完整的单元测试,并且我尝试手动调用该函数 component.ngOnInit 但结果是一样的
猜你喜欢
  • 1970-01-01
  • 2021-02-16
  • 2016-08-16
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多