【问题标题】:Testing Angular2 component @Input and @Output测试Angular2组件@Input和@Output
【发布时间】:2016-08-29 11:20:40
【问题描述】:

如何为 Angular2 简单表单组件构建测试:

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'user-form',
  template: `
    <input [(ngModel)]="user.name">
    <button (click)="remove.emit(user)">Remove</button>
  `
})
export class UserFormComponent {
  @Input() user: any;
  @Output() remove: EventEmitter<any> = new EventEmitter();
}

【问题讨论】:

    标签: angular angular2-testing


    【解决方案1】:

    Angular2 RC.5

    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { fakeAsync, tick, TestBed } from '@angular/core/testing';
    import { By } from '@angular/platform-browser/src/dom/debug/by';
    import { dispatchEvent } from '@angular/platform-browser/testing/browser_util';
    
    function findElement(fixture, selector) {
      return fixture.debugElement.query(By.css(selector)).nativeElement;
    }
    
    import { UserFormComponent } from './user-form.component';
    
    describe('User Form Component', () => {
      beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [TestComponent],
          imports: [FormsModule]
        });
      });
    
      it('should update', fakeAsync(() => {
        const fixture = TestBed.createComponent(TestComponent);
        fixture.detectChanges();
        tick();
        const input = findElement(fixture, 'input');
        expect(input.value).toEqual('Tom');
        input.value = 'Thomas';
        dispatchEvent(input, 'input');
        expect(fixture.debugElement.componentInstance.user.name).toEqual('Thomas');
      }));
    
      it('should remove', fakeAsync(() => {
        const fixture = TestBed.createComponent(TestComponent);
        fixture.detectChanges();
        tick();
        spyOn(fixture.debugElement.componentInstance, 'remove');
        const button = findElement(fixture, 'button');
        button.click();
        expect(fixture.debugElement.componentInstance.remove).toHaveBeenCalledWith(
          jasmine.objectContaining({id: 1})
        );
      }));
    });
    
    @Component({
      selector: 'test-component',
      directives: [UserFormComponent],
      template: `<user-form [user]="user" (remove)="remove($event)"></user-form>`
    })
    class TestComponent {
      user: any = { id: 1, name: 'Tom' };
      remove(user) { }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-07
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多