【问题标题】:How to test function inside ngOnInit如何在 ngOnInit 中测试函数
【发布时间】:2018-05-21 21:20:20
【问题描述】:

我的组件类很简单。它从父组件获取输入,并根据该输入从ngOnInit 中的 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

【问题讨论】:

    标签: angular angular-test


    【解决方案1】:

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

    it('should correctly wire url based on type1', () => {
       component.serviceType = 'type1';
       component.findServiceType()
    
       expect(component.serviceUrl)
           .toBe(TestFileEnumConstants.T1_URL)
    });
    

    【讨论】:

    • 感谢您的信息,我按照您说的更新了我的测试用例。我面临的真正问题是因为一个嘲弄的声明 - spyOn(component, 'findServiceType');。我已经更新了答案。
    【解决方案2】:

    问题是因为beforEach() 段中的SpyOn 语句。由于模拟函数没有返回任何数据,返回值不断得到undefined。问题陈述如下,我要评论spyOn 陈述:

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

    删除了这个功能并运行良好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      • 2021-10-15
      • 2019-03-08
      • 2016-08-09
      • 2020-12-14
      • 2017-11-20
      • 2016-05-25
      相关资源
      最近更新 更多