如何用Jasmine/Karma编写ngOnInit的单元测试 [英] How to write unit test for ngOnInit with Jasmine/Karma

查看:24
本文介绍了如何用Jasmine/Karma编写ngOnInit的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我的问题应该是在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();
    });
});

请帮帮我。

推荐答案

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

这篇关于如何用Jasmine/Karma编写ngOnInit的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆