【问题标题】:Angular unit test error ( finalSprintsList.map is not a function ) with jasmine karma茉莉业力的角度单元测试错误(finalSprintsList.map 不是函数)
【发布时间】:2019-12-17 09:52:57
【问题描述】:

我正在尝试为我的组件方法编写单元测试,即 populateSprintDropDown。这是我的组件代码

setResponseForButton() {
 let sortedList = this.teamboardService.sortSprintsBasedOnEndDate();
 this.populateSprintDropDown(sortedList);
}

//finalSprintList that is returned by service is = [{id: "3712", name: "DCT 3.128.1 Sp1 (11Dec-24Dec)", 
status: "ACTIVE", sprintLink: null, startDate: "2019-12-11"}]


populateSprintDropDown(finalSprintList: Array<any>) {
  this.sprintsList = (<Array<Sprint>>finalSprintList).map(sprint => ({ item_id: sprint.id, item_text: sprint.name }));
} 

测试:

  it('populate sprint in sprint dropdown upon button click', () => {
    let list = [{item_id: "3712", item_text: "DCT 3.128.1 Sp1 (11Dec-24Dec)"}]
    component.sprintsList  = list;
    const spy = spyOn(component, 'populateSprintDropDown').and.callThrough();
    component.setResponseForButton(); 
    expect(spy).toBeDefined();
    expect(spy).toHaveBeenCalled();
  });

但是当我运行我的测试时,我得到了这个错误:

TypeError: finalSprintsList.map 不是函数。 我不明白这是什么意思以及如何解决它。

【问题讨论】:

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


    【解决方案1】:

    你应该模拟方法teamboardService.sortSprintsBasedOnEndDate

    请注意,方法 component.populateSprintDropDown 不需要间谍,因为您可以检查通过此方法更新的值 component.sprintsList

    尝试如下重写你的测试:

    it('dropdown upon button click should update sprintsList', () => {
    
        // given
        const sortedList = [{
                              id: "3712",
                              name: "DCT 3.128.1 Sp1 (11Dec-24Dec)",
                              status: "ACTIVE",
                              sprintLink: null,
                              startDate: "2019-12-11"
                           }];
        spyOn(component.teamboardService, 'sortSprintsBasedOnEndDate').and.returnValue(sortedList);
    
        // when
        component.setResponseForButton(); 
    
        // then
        const expected = [{item_id: "3712", item_text: "DCT 3.128.1 Sp1 (11Dec-24Dec)"}];
        expect(component.sprintsList).toEqual(expected );
    });
    

    【讨论】:

    • 不,我首先调用 component.setResponseForButton 然后该成员进一步调用 populateSprintDropDown 方法,我想在其中创建 sprintsList
    • 我已经更新了这个问题。 sortedList 在组件级别不存在,它基本上是由服务返回的列表。
    • 现在您编辑了方法setResponseForButton,它清楚地表明了sortedList 的来源。我会相应地更新我的答案。 teamboardService.sortSprintsBasedOnEndDate() 不接受任何争论吗? Sprint界面长什么样子?
    猜你喜欢
    • 1970-01-01
    • 2016-06-15
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 2021-08-05
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多