Created
June 22, 2018 09:00
-
-
Save FrankMerema/8c84be6026df1ecf73fdc503fef331ed to your computer and use it in GitHub Desktop.
Testing Angular component with api service in OnInit (Spectator)
This file contains hidden or 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
import {HttpClient} from '@angular/common/http'; | |
import {Injectable} from '@angular/core'; | |
import {Observable} from 'rxjs/index'; | |
export interface someObject { | |
} | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class RestService { | |
constructor(private http: HttpClient) { | |
} | |
getAllStuffFromServer(): Observable<Array<SomeObject>> { | |
return this.http.get<Array<SomeObject>>(`/api/some/all`); | |
} | |
} |
This file contains hidden or 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
import {createTestComponentFactory, Spectator} from '@netbasal/spectator'; | |
import {of} from 'rxjs/index'; | |
import {RestService, someObject} from './rest.service'; | |
import {SomeComponent} from './some.component'; | |
describe('SomeComponent', () => { | |
const createComponent = createTestComponentFactory({ | |
component: SomeComponent, | |
mocks: [RestService] | |
}); | |
let spectator: Spectator<SomeComponent>; | |
beforeEach(() => { | |
spectator = createComponent(null, false); | |
spectator.get(RestService).getAllStuffFromServer.andReturn(of({})); | |
spectator.detectChanges(); | |
}); | |
it('should create', () => { | |
expect(spectator.component).toBeTruthy(); | |
}); | |
}); |
This file contains hidden or 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
import {Component, OnInit} from '@angular/core'; | |
import {RestService, SomeObject} from './rest.service'; | |
@Component({ | |
selector: 'some-component', | |
templateUrl: './some.component.html', | |
styleUrls: ['./some.component.scss'] | |
}) | |
export class SomeComponent implements OnInit { | |
someObjects: Array<SomeObjects>; | |
constructor(private restService: RestService) { | |
} | |
ngOnInit() { | |
this.restService.getAllStuffFromServer() | |
.subscribe(someObjects => { | |
this.someObjects = someObjects; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment