【问题标题】:How to write unit test for ngOnInit with Jasmine/Karma如何使用 Jasmine/Karma 为 ngOnInit 编写单元测试
【发布时间】:2022-01-30 00:47:49
【问题描述】:

实际上我的问题应该是“在 ngOnInit 中测试什么”。两天前我已经开始为我的公司代码编写单元测试。所以我不能向你展示整个确切的代码。我有一个组件:

filter-tree.component.ts

import { FilterPanelService } from 'src/app/core/services/filters/filter-panel.service';

@Component({
    ...
})
export class FilterTreeComponent implements OnInit {
    
    constructor(
        ...
        private filterPanelService: FilterPanelService
    ) {
        ...
    }

    ngOnInit() {
        this.filterPanelService.getEnableChildFilterNode$().subscribe(res => {
            this.isChildFilterNodeDisabled = res;
        });
    }
}

测试覆盖率非常低。我需要通过覆盖ngOnInit 来提升它。 看看我是否做得正确。覆盖报告仍然说它没有被覆盖。

filter-tree.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
...
import { FilterPanelService } from '.../filter-panel.service';

describe('FilterTreeComponent', () => {
    let component: FilterTreeComponent;
    let fixture: ComponentFixture<FilterTreeComponent>;
    let mockFilterPanelService;

    beforeEach(async(() => {
        mockFilterPanelService = jasmine.createSpyObj(['getEnableChildFilterNode$']);
        mockFilterPanelService.getEnableChildFilterNode$.and.returnValue(of(false));

        TestBed.configureTestingModule({
            imports: [...],
            declarations: [FilterTreeComponent,...],
            providers: [
                ...
                { provide: FilterPanelService, useValue: mockFilterPanelService }
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(FilterTreeComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should get response when the component loads', () => {
        mockFilterPanelService.getEnableChildFilterNode$.and.returnValue(of(false));
        fixture.detectChanges();
        expect(component.isChildFilterNodeDisabled).toBeFalsy();
    });
});

请帮帮我。

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    这是我找到的关于如何创建单元测试的最佳 youtube 播放列表: Advanced Web Apps 2019 | Unit Testing in Angular

    【讨论】:

    • 太棒了。这是我真正需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2023-03-24
    • 2015-11-10
    • 2017-05-27
    相关资源
    最近更新 更多