0

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();
}
4

1 に答える 1

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) { }
}
于 2016-08-29T11:20:40.913 に答える