如何测试具有带子组件对象的构造函数的组件 - 在Angular2中(Jasmine -Karma)

我正在使用具有构造函数的Angular 2组件中的Jasmine Karma编写测试用例 . 在这个构造函数中,我将其他组件对象作为参数传递 . 当试图访问其他组件的方法时,未定义 .

1. TestComponent

@Component({
    template: `<div></div>`
})
class TestComponent implements OnInit {
    constructor(public otherComponent: OtherComponent) {}
    ngOnInit() {}
    callMyFunction() {
        this.otherComponent.otherFunction();
    }
}

2. OtherComponent

@Component({
    selector: "other-component",
    template: `<div></div>`
})
export class OtherComponent implements OnInit {
    ngOnInit() {}
    public otherFunction(): void {
        console.log('test function called');
    }
}

3. Test Case

describe("TestComponent", () => {

    let comp: TestComponent;
    let fixture: ComponentFixture < TestComponent > ;
    let de: DebugElement;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [FormsModule],
            declarations: [TestComponent, OtherComponent],
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TestComponent);
        comp = fixture.componentInstance;
        de = fixture.debugElement;
        fixture.detectChanges();
    });

    fit("Should call otherFunction of OtherComponent.", () => {
        spyOn(comp.otherComponent, "otherFunction").and.callThrough();
        comp.callMyFunction();
        expect(comp.otherComponent.otherFunction).toHaveBeenCalled();
    });
});

请帮帮我 .

回答(0)