jasmine test cases dependency in angular 2 with stub - unit-testing

Here I'm new to angular 2 test cases with jasmine + karma and I'm following this testing guide I tried to write test case but unable to write correctly and getting routing error as test cases are going to server while running, although it should not.
There is a question similar to this but didn't help me to solve the problem. Please guide me.
Here is my component
import { Component, OnInit, ViewChild } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { Checklist } from './checklist';
import { Job } from '../+job/job';
import { OriginalService } from './original.service';
import { UserService } from '../core/user/user.service';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';
#Component({
selector: 'app-selector',
templateUrl: './original.component.html',
providers: [OriginalService]
})
export class OriginalComponent implements OnInit {
items = []
job: Job;
checklist: Checklist;
user: any;
shopId: any;
jobId: any;
constructor ( private orgService: OriginalService, private route: ActivatedRoute, private router: Router, userService: UserService) {
this.user = userService.user();
}
ngOnInit() {
this.route.params
.map(params => params['job_id'])
.subscribe(
job_id => this.jobId = job_id
);
this.getChecklist();
this.getJob();
}
getChecklist() {
this.orgService.getChecklists({
jobId: this.jobId
})
.then(checklist=> {
this.gotJobdata = true;
this.checklist = checklist.response})
.catch(error => this.error = error);
}
getJob(){
this.orgService.getJob({
jobId: this.jobId
})
.then(job => this.job = job.response)
.catch(error => this.error = error);
}
}
Here's my service
import { Injectable, ViewChildren } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { environment } from '../../environments/environment'
import 'rxjs/add/operator/toPromise';
import { Checklist } from './checklist';
import { Job } from '../+job/job';
import { UserService } from '../core/user/user.service';
#Injectable()
export class OriginalService {
shopId: any;
constructor(private http: Http, private userService: UserService ) {
this.shopId = userService.shopId();
}
getChecklists(svc): Promise<Checklist> {
return this.http.get(environment.apiUrl + this.shopId + '/jobs/' + svc.jobId + '/checklists_path/' + 'check_item.json')
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
getJob(svc): Promise<Job> {
return this.http.get(return environment.apiUrl + this.shopId + '/jobs/' + svc.jobId + '.json')
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
}
Here's the spec what I've tried:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { SharedModule } from '../shared/shared.module';
import { ModalModule } from 'ng2-bootstrap/ng2-bootstrap';
import { HttpModule } from '#angular/http';
import { Router, ActivatedRoute, Params } from '#angular/router';
import { ComponentLoaderFactory } from 'ng2-bootstrap/component-loader';
import { Subject } from 'rxjs/Subject';
import { UserService } from '../core/user/user.service';
import { OriginalService } from './original.service';
import { OriginalComponent } from './original.component';
describe('OriginalComponent', () => {
let component: OriginalComponent;
let fixture: ComponentFixture<OriginalComponent>;
let params: Subject<Params>;
let userService, orgService;
let userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User'}
};
beforeEach(async(() => {
params = new Subject<Params>();
TestBed.configureTestingModule({
imports: [ ModalModule.forRoot(), SharedModule, HttpModule ],
declarations: [ OriginalComponent ],
providers: [ OriginalService, UserService, ComponentLoaderFactory,
{ provide: Router, useValue: userServiceStub }, {provide: ActivatedRoute, useValue: { params: params }} ]
})
.compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(ChecklistComponent);
component = fixture.componentInstance;
fixture.detectChanges();
it('should create', () => {
expect(component).toBeTruthy();
});
});
Please correct me how to properly use routing in test cases or stubs where I'm doing wrong.

Related

Jasmine/karma test case are not running in an orderly manner using Angular5

When running the test case using jasmine/karma test cases. I am facing n issue which is before starting with the Login spec test case the other spec files are all called before completing the Login. It need to happen in an orderly manner which is like
1.Login
2.Dashboard
3.Order
etc.
Is there a way to do this.
login.spec.ts file
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { RouterModule, Router } from '#angular/router';
import { LoginComponent } from './login.component';
import { DebugElement } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { BrowserModule, By } from '#angular/platform-browser';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import { RouterTestingModule } from '#angular/router/testing';
import { APP_BASE_HREF } from '#angular/common';
import { LoginService } from './login.service';
import { HttpClientModule } from '#angular/common/http';
import { ApiService } from '../config/api.service';
import { ConfigService } from '../config/config.service';
import { Constants } from '../config/Constant';
import { SharedService } from '../shared/shared.service';
import { Http, BaseRequestOptions, ResponseOptions, Response, RequestMethod } from '#angular/http';
import { inject } from '#angular/core/testing';
import { MockBackend, MockConnection } from '#angular/http/testing';
describe('LoginComponent', () => {
let comp: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let de: DebugElement;
let el: HTMLElement;
let userNameEl: DebugElement;
let passwordEl: DebugElement;
let submitEl: DebugElement;
let loginService: LoginService = null;
let backend: MockBackend = null;
TestBed.overrideComponent(LoginComponent, {
set: {
providers: [
{
provide: LoginService,
useValue: loginService
},
{
provide: Router,
useClass: class { navigate = jasmine.createSpy('navigate'); }
}
]
}
});
beforeEach(async(() => {
// loginService = loginService;
// backend = mockBackend;
TestBed.configureTestingModule({
declarations: [
LoginComponent
],
imports: [
RouterModule.forRoot([{
path: '',
component: LoginComponent
}]),
BrowserModule,
FormsModule,
ReactiveFormsModule,
Ng2Bs3ModalModule,
RouterTestingModule,
HttpClientModule
],
providers: [
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backendInstance, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
},
LoginService,
ApiService,
ConfigService,
Constants,
SharedService,
{ provide: APP_BASE_HREF, useValue: '/' }
]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(LoginComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('form'));
el = de.nativeElement;
userNameEl = fixture.debugElement.query(By.css('input[id=InputEmail1]'));
passwordEl = fixture.debugElement.query(By.css('input[id=InputPassword1]'));
submitEl = fixture.debugElement.query(By.css('.login-btn'));
});
}));
beforeEach(inject([LoginService, MockBackend], (Service: LoginService, mockBackend: MockBackend) => {
loginService = Service;
backend = mockBackend;
}));
it('should create', () => {
expect(comp).toBeTruthy();
});
it('To check the initial value', () => {
expect(comp.submitted).toBe(false);
expect(comp.spinnerlogo).toBeFalsy();
expect(comp.data).toEqual({});
});
it(`entering value in username and password input controls`, () => {
userNameEl.nativeElement.value = 'admin';
passwordEl.nativeElement.value = 'admin';
fixture.detectChanges();
});
it('after entering value the button should enabled and click Action should happen', () => {
expect(submitEl.nativeElement.disabled).toBeFalsy();
const loginButtonSpy = spyOn(comp, 'onSubmit');
submitEl.triggerEventHandler('click', null);
expect(loginButtonSpy).toHaveBeenCalled();
});
it('calling onSubmit method after clicked the login button', () => {
comp.submitted = true;
comp.spinnerlogo = true;
comp.errorDiagnostic = null;
comp.mailerrorDiagnostic = null;
expect(comp.submitted).toBeTruthy();
expect(comp.spinnerlogo).toBeTruthy();
expect(comp.errorDiagnostic).toBeNull();
expect(comp.mailerrorDiagnostic).toBeNull();
});
it('#login should call endpoint and return it\'s result', (done) => {
backend.connections.subscribe((connection: MockConnection) => {
const options = new ResponseOptions({
body: JSON.stringify({ success: true })
});
connection.mockRespond(new Response(options));
// Check the request method
expect(connection.request.method).toEqual(RequestMethod.Post);
// Check the url
expect(connection.request.url).toEqual('/auth/login');
// Check the body
// expect(connection.request.text())
expect(connection.request.text()).toEqual(JSON.stringify({ username: 'admin', password: 'admin' }));
// Check the request headers
expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
});
loginService.login('admin', 'admin')
.subscribe((response) => {
console.log('response values are ---####------------ ', response);
// Check the response
expect(response.user.username).toEqual('admin');
expect(response.user.password).toEqual('admin');
// set value in sessionStorage
sessionStorage.setItem('currentUser', JSON.stringify(response));
sessionStorage.setItem('token', JSON.stringify(response.token));
sessionStorage.setItem('dismissOrders', 'false');
done();
},
(error) => {
expect(error).toThrowError();
});
});
});
the main problem is before executing the above file . The other spec file are executed
Thanks,
Kishan

Angular 4/CLI Unit test issue How to test a method of component that contains input object variable

Could somebody guide me how can I implement a unit test for the component below? I'm going to test the next() method of this component.When I implement a unit test for this function I got an error.Actually I'm beginner in unit test so I appreciate if somebody implements a Professional unit test on this sample which be reference for me for other components.
component file:
import { Component, Input, OnInit } from '#angular/core';
import { Client, ClientMetadata } from '../../shared/clients/client.model';
import { ClientService } from '../../shared/clients/client.service';
import { HomeRoutingService } from '../home-routing/home-routing.service';
import { FormValidationService } from "../../shared/form-validation/form-
validation.service";
import { FormBuilder} from '#angular/forms';
#Component({
selector: 'email-form',
templateUrl: './email-form.component.html',
styleUrls: ['./email-form.component.css', '../home.component.css'],
})
export class EmailFormComponent implements OnInit{
#Input() client: Client;
isClickedIncognito: boolean;
isClickedNext: boolean;
constructor(
private clientService: ClientService,
private homeRoutingService: HomeRoutingService,
public fv: FormValidationService
) { }
ngOnInit() {
this.isClickedIncognito = false;
this.isClickedNext = false;
// form is builded in fv service
this.fv.buildFormEmail();
}
next(anonymous: boolean): void {
document.body.style.cursor = 'wait';
this.client.anonymous = anonymous === true ? 1 : 0;
// If client is anonymous go directly to measurement form
if (anonymous) {
this.isClickedIncognito = true;
this.saveClient();
this.homeRoutingService.next(this.constructor.name, { anonymous:
true });
}
// Check if client exists in DB ; check if has password ;
else {
this.isClickedNext = true;
this.clientService.checkExist(this.client.email)
.then(exists =>
this.handleExist(exists)
);
}
}
saveClient(): void {
let gender = new ClientMetadata('gender', environment.gender);
(this.client.clientMetadatas = this.client.clientMetadatas ?
this.client.clientMetadatas : []).push(gender);
if (this.client.anonymous === 1)
this.client.email = null;
else if (this.client.email === null) { return; }
this.clientService.addClient(this.client)
.then(client => this.client = client);
}
}
spec file :
import { ComponentFixture, TestBed, async } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { DebugElement, NO_ERRORS_SCHEMA } from '#angular/core';
import { EmailFormComponent } from './email-form.component';
import { ClientService } from '../../shared/clients/client.service';
import { HomeRoutingService } from '../home-routing/home-routing.service';
import { FormValidationService } from "../../shared/form-validation/form-
validation.service";
import { FormBuilder } from '#angular/forms';
import { Client, ClientMetadata } from '../../shared/clients/client.model';
import { TranslateModule, TranslateStaticLoader, TranslatePipe,
TranslateLoader } from 'ng2-translate';
import { Http } from '#angular/http';
export function createTranslateLoader(http: Http) {
return new TranslateStaticLoader(http, '../../assets/i18n/', '.json');
}
describe('EmailFormComponent', () => {
let component: EmailFormComponent;
let fixture: ComponentFixture<EmailFormComponent>;
let de: DebugElement;
let el: HTMLElement;
let formService: FormValidationService;
let clientService: ClientService;
let ClientEl: Client;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [EmailFormComponent],
providers: [FormValidationService,
ClientService,
HomeRoutingService,
FormValidationService,
FormBuilder
// { provide: ClientService, useValue: ClientServiceStub },
// { provide: HomeRoutingService, useValue:
HomeRoutingServiceStub },
// { provide: FormValidationService, useValue: FormValidationServiceStub }
],
schemas: [NO_ERRORS_SCHEMA],
imports: [TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
})]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(EmailFormComponent);
component = fixture.componentInstance;
// formService = fixture.debugElement.injector.get(FormValidationService);
// formService.buildFormEmail();
// clientService = fixture.debugElement.injector.get(ClientService);
// fixture.detectChanges();
});
it('should component works well', async(() => {
const fixture = TestBed.createComponent(EmailFormComponent);
const comp = fixture.debugElement.componentInstance;
expect(comp).toBeTruthy();
}));
it('should be correct', () => {
let anonymous = true;
component.next(anonymous);
//console.log(component.isClickedIncognito);
expect(component.isClickedIncognito).toBe(true);
//expect(true).toBe(true);
});
});
error (when I comment fixture.detectChanges()):
Cannot set property 'anonymous' of undefined
error (when I put fixture.detectChanges()):
Cannot read property 'email' of undefined

Angular 2 Observable Service Karma Jasmine Unit Test not working

I am a newbie to Angular 2 and Karma + Jasmine unit tests. I cannot figure out what semantic error I have made in order to make this unit test use the mocked response. In the console, when "expect(items[0].itemId).toBe(2);" is run, it says items[0].itemId is undefined.
Would someone be able to help me out or point me in the right direction? Please let me know if you need any additional information. Thanks!
item.ts
export class Item {
itemId: number;
itemName: string;
itemDescription: string;
}
item.service.ts
import { Injectable, Inject } from '#angular/core';
import { Headers, Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import { Item } from './item';
#Injectable()
export class ItemService {
private headers = new Headers({'Content-Type': 'application/json'});
constructor(
private http: Http)
{
}
getItems(listOptions: Object): Observable<Item[]> {
return this.http.post('/listItems', listOptions, {headers:this.headers})
.map(response => response.json() as Item[])
}
}
item.service.spec.ts
import { TestBed, fakeAsync, inject, tick } from '#angular/core/testing';
import { MockBackend } from '#angular/http/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import { ItemService } from './item.service';
import { Item } from './item';
describe('ItemService', () => {
let mockResponse, matchingItem, connection;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ItemService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
deps: [MockBackend, BaseRequestOptions]
},
// { provide: XHRBackend, useClass: MockBackend }
]
});
const items = [
{
"itemId":2,
"itemName":"test item1",
"itemDescription":"hello hello"
},
{
"itemId":1,
"itemName":"name2124111121",
"itemDescription":"description212412112"
}
];
mockResponse = new Response(new ResponseOptions({body: {data: items}, status: 200}));
});
describe('getItems', () => {
//Subscribing to the connection and storing it for later
it('should return all the items',inject([ItemService, MockBackend], (service: ItemService, backend: MockBackend) => {
backend.connections.subscribe(connection => {
connection.mockRespond(mockResponse);
});
service.getItems({isActive: true, sortColumn: "lastModifiedDateUtc", sortOrder: "desc"})
.subscribe((items: Item[]) => {
expect(items.length).toBe(2);
});
}));
});
});
Plunkr: https://plnkr.co/edit/m7In2eVh6oXu8VNYFf9l?p=preview
(There are some errors with the Plunkr I need help with as well but the main files are there)
The mockResponse body did not match the actual response body, that is why I was getting the error.
mockResponse = new Response(new ResponseOptions({body: {data: items}, status: 200})); should be mockResponse = new Response(new ResponseOptions({body: items, status: 200}));

Angular2 Testing

Stuck on how to test a component that has alot of third party dependencies. Pretty sure I'm approaching it the wrong way, I'm not sure where to start on this. Here's the component:
import { Component, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
import { GameService } from '../game.service';
import { environment } from '../../../environments/environment';
import { ActivatedRoute } from '#angular/router';
import { SlimLoadingBarService } from 'ng2-slim-loading-bar';
#Component({
selector: 'app-list',
templateUrl: 'list.component.html',
styleUrls: ['list.component.scss']
})
export class ListComponent implements OnInit {
config = environment.config;
games;
headers;
params = {
searchTerm: '',
searchOwner: '',
searchType: '',
order: 'name',
orderType: 'DESC',
currentPage: 1,
page: 1
};
pages;
totalRecords;
recordsPerPage = 25;
exportUrl;
personasPage = 1;
searchUrl = environment.config.apiUrl + 'personas/';
public buffer: any;
public personas: any;
buttonSpinner: string = 'none';
constructor(
private gameService: GameService,
private http: Http,
private route: ActivatedRoute,
private loadingBar: SlimLoadingBarService
) { }
ngOnInit() {
this.getListing();
this.getPersonas();
}
sort(e, order) {
e.preventDefault();
this.params.orderType = (order === this.params.order && this.params.orderType === 'DESC') ? 'ASC' : 'DESC';
this.params.order = order;
this.params.page = this.params.currentPage = 1;
this.getListing();
}
updateListing(page) {
this.params.page = this.params.currentPage = page;
this.getListing();
}
getListing() {
this.loadingBar.start();
this.gameService.getGames(this.params)
.subscribe((res) => {
this.loadingBar.complete();
this.buttonSpinner = 'none';
this.games = res.json();
this.headers = res.headers;
this.totalRecords = this.headers.get('x-total');
this.recordsPerPage = this.headers.get('x-limit');
this.exportUrl = this.gameService.getExportLink(this.params);
});
}
getPersonas() {
this.http.get(this.searchUrl + '?page=' + this.personasPage)
.map((res: Response) => res.json())
.subscribe((d: {}) => {
this.buffer = d;
if (this.personas === undefined) {
this.personas = this.buffer;
// console.log(this.personas);
this.personasPage += 1;
this.getPersonas();
} else {
for (let key in this.buffer) {
this.personas.push(this.buffer[key]);
}
this.personasPage += 1;
if (this.buffer.length === 25) {
this.getPersonas();
}
}
});
}
onSubmitSearch() {
this.buttonSpinner = 'searching';
this.params.page = this.params.currentPage = 1;
this.getListing();
}
clearSearch(e) {
e.preventDefault();
this.buttonSpinner = 'clearing';
this.params.searchTerm = '';
this.params.searchType = '';
this.params.searchOwner = '';
this.params.page = this.params.currentPage = 1;
this.getListing();
}
}
Here's the Test I've tried writing:
import { TestBed, async, ComponentFixture } from '#angular/core/testing';
import {} from 'jasmine';
import { Http } from '#angular/http';
import { ActivatedRoute, RouterModule } from '#angular/router';
import { CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { ListComponent } from './list.component';
import { GameService } from '../game.service';
import { PageitComponent } from '../../shared/pageit/pageit.component';
import { SlimLoadingBarService } from 'ng2-slim-loading-bar';
import { LaddaModule } from 'angular2-ladda';
describe('ListComponent', () => {
let gameService, http, route, loadingBar;
let component: ListComponent;
let fixture: ComponentFixture<ListComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ ListComponent, PageitComponent ],
providers: [
{ provide: GameService, useValue: gameService }, { provide: Http, useValue: http }, { provide: ActivatedRoute, useValue: route },
{ provide: SlimLoadingBarService, useValue: loadingBar }
],
imports: [FormsModule, LaddaModule, RouterModule]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ListComponent);
component = fixture.componentInstance;
});
it('should create an instance of the component', () => {
component.ngOnInit();
expect(component).toBeDefined();
});
});
So far, I've got it to recognize the init, now it's breaking because of this.loadingBar.start(); inside the getListing function.
Just mock all the services and test the behavior of the component by checking that it makes the correct service class, by using expect(mockService.someMethod).toHaveBeenCalled().
For example
let loadingBar: SlimLoadingBarService;
let gameService: GameService;
beforeEach(() => {
loadingBar = {
start: jasmine.createSpy('start'),
complete: jasmine.createSpy('complete')
};
gameService = {
getGames: (params) => Observable.of(whatever)
};
TestBed.configureTestingModule({
providers: [
{ provide: SlimLoadingBarService, useValue: loadingBar },
{ provide: GameService, useValue: gameService }
]
})
})
it('..', () -> {
component.getListing();
expect(loadingBar.start).toHaveBeenCalled();
// component calls gameService.getGames is called, wait for async
// to finish by called fixture.whenStable
fixture.whenStable().then(() => {
expect(loadingBar.complete).toHaveBeedCalled();
})
})
For you Http call in the component, I would abstract that into a service so that you can mock that service.

angular 2 RC4- Cannot resolve all parameters for 'Router'

I have written a test for my component and it is failing with
Error: Cannot resolve all parameters for 'Router'(?, ?, ?, ?, ?, ?,
?). Make sure that all the parameters are decorated with Inject or
have valid type annotations and that 'Router' is decorated with
Injectable.
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { Supplier } from './supplier';
import { SupplierService } from './supplier.service';
import { AppService } from '../shared/app.service';
#Component({
moduleId: module.id,
selector: 'supplier-form',
templateUrl: './supplier-form.component.html',
styleUrls: ['./supplier-form.component.css']
})
export class SupplierFormComponent implements OnInit {
private countries: any;
private model: Supplier;
private errorMessage: string;
private submitted: boolean = false;
private active: boolean = true;
constructor(private appService: AppService, private supplierService: SupplierService, private router: Router, private route: ActivatedRoute) {
this.model = new Supplier();
this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
if (!isNaN(id))
this.supplierService.getSupplierById(id)
.subscribe(supplier => this.model = supplier, error => this.errorMessage = error);
});
}
ngOnInit() {
this.getCountries();
}
private getCountries() {
this.appService.getCountry()
.subscribe(countries => this.countries = countries.items,
error => this.errorMessage = error);
}
private navigateToHomePage(supplier) {
if (supplier) {
let link = [''];
this.router.navigate(link);
}
}
private onSubmit(): void {
this.submitted = true;
this.supplierService.saveSupplier(this.model).subscribe(
supplier => this.navigateToHomePage(supplier),
error => this.errorMessage = error);
}
}
very simple component all its doing is getting countries from a service which is using Http call and calling save method on another service which is also http call. I am mocking those services with my Mock classes. below is my test code.
import { By } from '#angular/platform-browser';
import { DebugElement, provide } from '#angular/core';
import { disableDeprecatedForms, provideForms } from '#angular/forms';
import { Router, ActivatedRoute } from '#angular/router';
import * as Rx from 'rxjs/Rx';
import {
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject, addProviders,
TestComponentBuilder, ComponentFixture
} from '#angular/core/testing';
import { SupplierFormComponent } from './supplier-form.component';
import { SupplierService } from './supplier.service';
import { AppService } from '../shared/app.service';
describe('Component: Supplier', () => {
var builder;
beforeEachProviders(() => {
return [
disableDeprecatedForms(),
provideForms(),
Router, ActivatedRoute,
provide(AppService, { useClass: MockAppService }),
provide(SupplierService, { useClass: MockSupplierService })
];
});
beforeEach(inject([TestComponentBuilder], (tcb) => {
builder = tcb;
}));
it('should create Supplier Component', async(() => {
/*.overrideProviders(
SupplierFormComponent,
[{ provide: AppService, useClass: MockAppService }]
)*/
builder.createAsync(SupplierFormComponent)
.then((fixture: ComponentFixture<SupplierFormComponent>) => {
fixture.detectChanges
var compiled = fixture.debugElement.nativeElement;
console.log(compiled);
})
.catch((error) => {
console.log("error occured: " + error);
});
}));
});
class MockAppService {
public name = "Injected App Service";
public fakeResponse: any = [{ "id": 1, "name": "uk" }];
public getCountry() {
return this.fakeResponse;
}
}
class MockSupplierService {
public name = "Injected Supplier Service";
saveSupplier(supplier: any): boolean {
return true;
}
}
any idea how can i mock router properly with RC.4.