首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >对输出绑定不起作用的最简单测试

对输出绑定不起作用的最简单测试
EN

Stack Overflow用户
提问于 2019-05-30 15:10:38
回答 1查看 49关注 0票数 0

我正在用一个按钮测试一个非常简单的组件。当单击按钮时,它会发出一个(@output)事件,然后调用父级的回调(chatMessageFeedbackHandler)。没什么不寻常的。

但由于某些原因,下面的测试不起作用。我只是在测试单击子对象的chatMessageFeedbackHandler时是否调用了父对象的button#test1

注意:如果您注释了以下任一测试,则会成功运行:

  1. 线路:子1.1和子1.2
  2. 线路:父1.1和父1.2

测试:

代码语言:javascript
复制
import {async, ComponentFixture, fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing';
import {Component, DebugElement} from "@angular/core";
import {AppComponent} from './app.component';
import {By} from '@angular/platform-browser';

function createHostComponent(): ComponentFixture<HostComponent> {
  const fixture = TestBed.createComponent(HostComponent);
  fixture.detectChanges();
  return fixture as ComponentFixture<HostComponent>;
}

fdescribe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<HostComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HostComponent, AppComponent],
    })
    // .compileComponents();
  }));

  beforeEach(() => {
    // fixture = TestBed.createComponent(ChatFeedbackComponent);
    fixture = createHostComponent();

  });

  fit('should emit chatMessageFeedback$ true when clicked on like button', fakeAsync(() => {
    const appComponent = fixture.debugElement.query(By.directive(AppComponent)) as DebugElement;
    // spyOn(appComponent.componentInstance,'chatFeedbackClicked');//LINE: parent 1.1
    spyOn(fixture.componentInstance,'outputHandler'); //LINE: child 1.1
    fixture.debugElement.nativeElement.querySelector('#test1').click();
    tick(500);
    flushMicrotasks();
    fixture.detectChanges();
    // expect(appComponent.componentInstance.chatFeedbackClicked).toHaveBeenCalled();//LINE: parent 1.2
    expect(fixture.componentInstance.outputHandler).toHaveBeenCalledWith(true);//LINE: child 1.2
  }));

});


@Component({selector: 'host-for-test', template: `
    <app-root (chatMessageFeedback$)="outputHandler($event)"></app-root>
  `})
class HostComponent {

  outputHandler(data) {
    alert();
  }
}

子组件:

代码语言:javascript
复制
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button id="test1" (click)="chatFeedbackClicked(true)">Test</button>
  `,
})
export class AppComponent {
  @Output() chatMessageFeedback$ = new EventEmitter();

  chatFeedbackClicked(isFeedbackPositive: boolean) {
    this.chatMessageFeedback$.emit(isFeedbackPositive);
  }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56373420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档