Angular 角度-通过@ViewChild为引用子组件的组件编写集成测试

Angular 角度-通过@ViewChild为引用子组件的组件编写集成测试,angular,unit-testing,jasmine,karma-jasmine,Angular,Unit Testing,Jasmine,Karma Jasmine,我必须编写一个测试用例,在其中调用函数中的函数 这是我想要编写测试用例的主要组件。想要为openModel函数编写单元测试 @ViewChild(SecondComponent)公共SecondComponent:SecondComponent; openModal(){ this.secondComponent.showmodel(); }好吧,这里您真正想做的是为您的main组件的openmodel编写集成测试。所以你应该问问自己,这个方法在做什么 编写自动化测试的经验法则: 您应该始终专

我必须编写一个测试用例,在其中调用函数中的函数

  • 这是我想要编写测试用例的主要组件。想要为
    openModel
    函数编写单元测试
  • @ViewChild(SecondComponent)公共SecondComponent:SecondComponent;
    openModal(){
    this.secondComponent.showmodel();
    
    }
    好吧,这里您真正想做的是为您的
    main组件
    openmodel
    编写集成测试。所以你应该问问自己,这个方法在做什么

    编写自动化测试的经验法则: 您应该始终专注于测试单元(
    mainponent
    在本例中)
    正在做什么。在本例中,所有其他内容(
    SecondComponent
    )都可以模拟

    现在回答您在编写测试时要问的问题是,
    openModal
    方法正在调用
    main组件的
    secondComponent
    属性上名为
    showmodel
    的函数

    因此,根据我们的经验法则,我们将模拟
    secondComponent
    上的
    showmodel
    方法,我们可以从
    fixture
    componentInstance
    属性中获得该方法

    因此,您的集成测试应该如下所示:

    从'@angular/core/testing'导入{async,ComponentFixture,TestBed};
    从“./main.component”导入{MainComponent};
    从“/../modal/modal.component”导入{ModalComponent};
    从“/../second/second.component”导入{SecondComponent};
    描述('main component',()=>{
    let组件:主组件;
    let夹具:组件夹具;
    beforeach(异步(()=>{
    TestBed.configureTestingModule({
    声明:[MainComponent、ModalComponent、SecondComponent]
    })
    .compileComponents();
    }));
    在每个之前(()=>{
    fixture=TestBed.createComponent(主组件);
    组件=fixture.componentInstance;
    fixture.detectChanges();
    });
    它('应该创建',()=>{
    expect(component.toBeTruthy();
    });
    描述('openModal',()=>{
    它('应该调用组件上的'secondComponent'属性上的'showmodel'方法',()=>{
    //安排
    设secondComponent=component.secondComponent;
    设spy=spyOn(第二个组件“showmodel”);
    //表演
    openModal();
    //断言
    期望(间谍)。已被调用();
    });
    });
    
    });组件是一个测试平台组件吗?不,它是我要测试的主要组件阅读这是一个组件测试指南。您可以模拟您的模块、组件和服务。还可以将您的服务注入到it中。例如
    fixture.detectChanges()检测测试组件上的更改,以便查看是否调用了模态。