【发布时间】: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