2

我的组件类很简单。它从父组件获取输入,并根据该输入从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即使在调用更改检测之后,输入也会出现。

4

2 回答 2

1

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

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

删除此功能并正常工作。

于 2018-05-18T13:44:00.613 回答
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)
});
于 2018-05-16T20:58:36.100 回答