Last active
November 23, 2016 19:25
-
-
Save briebug/2cc25b71d79e9ee95ac13101f60a65d0 to your computer and use it in GitHub Desktop.
Angular 2 Test Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* tslint:disable:no-unused-variable */ | |
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; | |
import {By} from '@angular/platform-browser'; | |
import {DebugElement} from '@angular/core'; | |
import {WelcomeComponent} from './welcome.component'; | |
import {UserService} from '../../services/user.service'; | |
import {userServiceMock} from '../../mocks'; | |
describe('WelcomeComponent', () => { | |
let component: WelcomeComponent; | |
let fixture: ComponentFixture<WelcomeComponent>; | |
let de: DebugElement; | |
let el: HTMLElement; | |
let userService; | |
beforeEach(async(() => { | |
TestBed.configureTestingModule({ | |
declarations: [ | |
WelcomeComponent | |
] | |
}).overrideComponent(WelcomeComponent, { | |
set: { | |
providers: [ | |
{provide: UserService, useClass: userServiceMock} | |
] | |
} | |
}).compileComponents(); | |
})); | |
beforeEach(() => { | |
fixture = TestBed.createComponent(WelcomeComponent); | |
component = fixture.componentInstance; | |
// query for the welcome <h1> by CSS element selector | |
de = fixture.debugElement.query(By.css('h3.welcome')); | |
el = de.nativeElement; | |
// get an instance of the userService injected into the component | |
userService = fixture.debugElement.injector.get(UserService); | |
}); | |
it('should create', () => { | |
// arrange | |
// act | |
// assert | |
expect(component).toBeTruthy(); | |
}); | |
it('should create', () => { | |
// arrange | |
// act | |
// assert | |
expect(component.welcome).toBe('-- not initialized yet --'); | |
}); | |
it('should welcome user when logged in', () => { | |
// arrange | |
// act | |
fixture.detectChanges(); | |
// assert | |
expect(component.welcome).toBe('Welcome, Test User'); | |
}); | |
it('should ask user to login when not logged in', () => { | |
// arrange | |
userService.isLoggedIn = false; | |
// act | |
fixture.detectChanges(); | |
// assert | |
expect(component.welcome).toBe('Please log in.'); | |
}); | |
it('should welcome new user when logged in', () => { | |
// arrange | |
userService.user.name = 'Bob Marley'; | |
// act | |
fixture.detectChanges(); | |
// assert | |
expect(component.welcome).toBe('Welcome, Bob Marley'); | |
}); | |
it('should display a different test title', () => { | |
fixture.detectChanges(); | |
expect(el.textContent).toContain('Welcome, Test User'); | |
}); | |
}); |
Author
briebug
commented
Nov 23, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment