【问题标题】:Calling function by triggering selectChange event Angular testing通过触发 selectChange 事件调用函数 Angular 测试
【发布时间】:2018-03-19 15:44:47
【问题描述】:

我开始使用 Angular(v4.0.0) 开发一个小项目。在这个项目中,我正在添加单元测试。我阅读了angular testing documentation,现在对如何用 Angular 编写单元测试有了基本的了解。

在这方面,我正在努力为一个在 html 中触发 selectChange 事件的函数编写测试用例。

html的代码sn-p

html content
        <div class="metabs">
            <md-tab-group (selectChange)="selectMetabs($event)" [selectedIndex]="selectedIndex" *ngIf="!showAllMetabs">
                    <md-tab [label]="metab.name" *ngFor="let metab of dashboards"></md-tab>                        
            </md-tab-group>                    
        </div>

ts 的代码 sn-p

// Corresponding ts containing selectMetabs function

selectMetabs(event) {
  console.log("--in select metabos--");  // this console is not getting printed
  // rest of the code 
}

现在我为此编写了测试用例:

describe('DashboardComponent', () => {
    let fixture: ComponentFixture<DashboardComponent>;
    let comp: DashboardComponent;
    let de: DebugElement;
    let el: HTMLElement;
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                DashboardComponent,
            ],
            providers: [
            ],
            imports: [
                BrowserAnimationsModule,
                AppMaterialModule,
            ],
            schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ],
        }).compileComponents()
        fixture = TestBed.createComponent(DashboardComponent)
        comp = fixture.componentInstance
    }))

it("should check selectMetabs function call", async(() => {
    comp.showAllMetabs = false;
    fixture.detectChanges();
    let de = fixture.debugElement.query(By.css('.metabs > md-tab-group'));
    let spy = spyOn(comp, 'selectMetabs');
    de.triggerEventHandler('selectChange', {index: 0});
    expect(spy).toHaveBeenCalled(); // pass test case
    expect(spy).toHaveBeenCalledTimes(1); // pass test case
    expect(comp.selectMetabolite).toHaveBeenCalledWith({index:0}); // pass test case
}))

我的这些测试用例都通过了,这向我保证 triggerEvent 正在工作。

我的困惑是,如果 selectMetabs 函数被调用,他们为什么没有打印控制台语句。

另外,这个函数也没有被测试覆盖。

我无法理解为什么会这样。我是角度测试的新手,这个问题让我很困惑。如果我遗漏了什么或需要提供更多信息,请告诉我。

我们将不胜感激有用的建议。谢谢!!

【问题讨论】:

    标签: angular unit-testing jasmine angular-test


    【解决方案1】:

    发生这种情况的原因是因为您正在通过let spy = spyOn(comp, 'selectMetabs'); 模拟组件的selectMetabs 方法。这也是您正在测试的内容。

    就单元/集成测试而言,这是非常错误的。这是因为,在单元/集成测试中,您不应该模拟被测 thing 的方法(此处是您的组件)。您应该只模拟您的组件所依赖的其他事物的方法(例如服务的方法)。

    一旦你删除了这个间谍let spy = spyOn(comp, 'selectMetabs');,它应该调用你的组件的方法并且它应该被覆盖。

    现在出现的问题是:在这种情况下您应该期待什么?

    好吧,您正在组件的 selectMetabs 方法中执行 console.log("--in select metabos--");。因此,您可以模拟 console.log,然后期望它已被调用。

    希望对您有所帮助。

    【讨论】:

    • 感谢您的回复!我会检查一次,然后告诉你!
    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多