0

How can I structure tests for Angular2 simple form component:

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

1 Answer 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) { }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Initial Angular RC.5 sample based on github.com/chickentang/Angularjs-2.0_tang/blob/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.