如何在 ngOnInit 中测试函数

How to test function inside ngOnInit

我的组件class很简单。它从父组件获取输入,并根据该输入从 ngOnInit 中的 ENUM 解析参数
我的组件 class:

export class TestComponent implements OnInit {
@Input() serviceType: string;
serviceUrl : string;

ngOnInit() {
        this.findServiceType();
    }
    
findServiceType= () => {
        if (this.serviceType) {
            if (this.serviceType === 't1') {
                this.serviceUrl = TestFileEnumConstants.T1_URL;
            }else if (this.serviceType === 't2') {
                this.serviceUrl = TestFileEnumConstants.T2_URL;
            }
        }
    }
    
 }

我的测试 Class:

describe('testcomponent', () => {

    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;
    let mockService = <Serv1>{};
    
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [FormsModule],
            declarations: [
                TestComponent, TestChildComponent],
            providers: [
                { provide: MockService, useValue: mockService }
                ]
        });
        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
    });
    
    it('should create testcomponent', () => {
        expect(component).toBeDefined();
    });
    
     describe('testType1',  () => {
        beforeEach( () => {
            spyOn(component, 'findServiceType');
            
        });
        it('should correctly wire url based on type1', () => {
            component.serviceType = 'type1';
            fixture.detectChanges(); 
            expect(component.findServiceType).toHaveBeenCalled();
            expect(component.serviceUrl).toBe(TestFileEnumConstants.T1_URL)
        });
    });
    
    }


问题是 serviceUrl 没有得到 poluplated,因为 'serviceType' - 即使在调用更改检测之后,输入也会以 undefined 的形式出现。

您应该创建两个测试而不是一个。第一个测试 this.findServiceType(); 是否在 ngOnInit 上调用,然后第二个测试单独测试 findServiceType 的功能。

it('should correctly wire url based on type1', () => {
   component.serviceType = 'type1';
   component.findServiceType()

   expect(component.serviceUrl)
       .toBe(TestFileEnumConstants.T1_URL)
});

问题是由于 beforEach() 段中的 SpyOn 语句引起的。由于模拟函数未 returning 任何数据,因此 return 值继续得到 undefined。问题陈述如下,我要注释spyOn语句:

beforeEach( () => {
            // spyOn(component, 'findServiceType');
            
        });

删除了这个功能并且工作正常。