如何在ngOnInit中测试函数

时间:2018-05-16 20:48:30

标签: angular angular-test

我的组件类很简单。它接收来自父组件的输入,并根据该输入从ngOnInit内的ENUM中解析出一个参数
我的Component类:

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;
            }
        }
    }
    
 }

我的测试班:

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没有得到解决,因为'serviceType' - 即使在调用更改检测之后,输入也会变为undefined

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

问题在于SpyOn细分中的beforEach()声明。由于mock函数没有返回任何数据,因此返回值继续获取undefined。问题陈述如下,我必须评论spyOn陈述:

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

删除此功能并且工作正常。