首页 > 解决方案 > 如何在 ngOnInit 中测试函数

问题描述

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

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即使在调用更改检测之后,输入也会出现。

标签: angularangular-test

解决方案


问题是因为SpyOn该部分中的一个声明beforEach()。由于模拟函数没有返回任何数据,因此返回值不断获取undefined。问题陈述如下,我必须评论该spyOn陈述:

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

删除此功能并正常工作。


推荐阅读