NullInjectorError while testing - javascript

I have the following problem while running ng test in Angular 12:
NullInjectorError: R3InjectorError(DynamicTestModule)[BaseURL ->
BaseURL]: NullInjectorError: No provider for BaseURL! error
properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'BaseURL',
'BaseURL' ] }) NullInjectorError:
R3InjectorError(DynamicTestModule)[BaseURL -> BaseURL]:
NullInjectorError: No provider for BaseURL!
at NullInjector.get (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:11101:1)
at R3Injector.get (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:11268:1)
at R3Injector.get (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:11268:1)
at NgModuleRef$1.get (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:25332:1)
at Object.get (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:25046:1)
at lookupTokenUsingModuleInjector (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:3342:1)
at getOrCreateInjectable (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:3454:1)
at ɵɵdirectiveInject (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:14737:1)
at NodeInjectorFactory.MenuComponent_Factory [as factory] (ng:///MenuComponent/ɵfac.js:5:7)
at getNodeInjectable (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/ivy_ngcc/fesm2015/core.js:3549:1)
Error: Expected undefined to be truthy.
at
at UserContext. (http://localhost:9876/karma_webpack/webpack:/src/app/menu/menu.component.spec.ts:46:23)
at ZoneDelegate.invoke (http://localhost:9876/karma_webpack/webpack:/node_modules/zone.js/fesm2015/zone.js:372:1)
at ProxyZoneSpec.onInvoke (http://localhost:9876/karma_webpack/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:287:1)
The code for the spec.ts is:
import { ComponentFixture, TestBed } from '#angular/core/testing';
import { MenuComponent } from './menu.component';
import { DishService } from '../services/dish.service';
describe('MenuComponent', () => {
let component: MenuComponent;
let fixture: ComponentFixture<MenuComponent>;
const mockDishService = {
getDishes: () => {
return {
id: '000',
name: 'nnnnn'
}
}
}
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [],
declarations: [ MenuComponent ],
providers: [
{ provide: DishService, useValue: mockDishService },
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MenuComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
The code of the component is:
import { Component, OnInit, Inject } from '#angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
import { flyInOut, expand } from '../animations/app.animation';
#Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss'],
// tslint:disable-next-line:use-host-property-decorator
host: {
'[#flyInOut]': 'true',
'style': 'display: block;'
},
animations: [
flyInOut(),
expand()
]
})
export class MenuComponent implements OnInit {
dishes!: Dish[];
errMess: string;
constructor(private dishService: DishService,
#Inject ('BaseURL') public baseURL) { }
ngOnInit(): void {
this.dishService.getDishes().subscribe((dishes => this.dishes = dishes), errMess => this.errMess = <any>errMess);
}
}
I'm using the baseURL to obtain the information for a db.json file while running json-server --watch db.json to simulate that I get the information from the server, so I have a shared .ts file named baseurl.ts with the following code:
export const baseURL = 'http://localhost:3000';
And in the app.module.ts I import the const
import { baseURL } from './shared/baseurl';
and I add it as a provider in the same app.module.ts file:
providers: [
{ provide: 'BaseURL', useValue: baseURL }
],
I will appreciate someone is help on this error

Issue 1: NullInjectorError
This error message shows as your DishComponent requires BaseURL to be injected [#Inject ('BaseURL')].
NullInjectorError: R3InjectorError(DynamicTestModule)[BaseURL -> BaseURL]: NullInjectorError: No provider for BaseURL!
Solution for Issue 1
Ensure that you add BaseURL in providers section for unit testing.
const baseUrl = "your Base URL";
beforeEach(async () => {
await TestBed.configureTestingModule({
...
providers: [
{ provide: DishService, useValue: mockDishService },
{ provide: 'BaseURL', useValue: baseUrl },
]
})
.compileComponents();
});
Issue 2: Return wrong value for mockDishService.getDishes()
From MenuComponent, it is expected that the dishService.getDishes() return the value of Observable<Menu[]> or Observable<any[]> type.
dishes!: Dish[];
this.dishService.getDishes().subscribe((dishes => this.dishes = dishes), errMess => this.errMess = <any>errMess);
While the mockDishService.getDishes() returns the value of any or Menu type, which the data returned was unmatched.
const mockDishService = {
getDishes: () => {
return {
id: '000',
name: 'nnnnn',
};
},
};
Hence you will get this error message as below:
TypeError: this.dishService.getDishes(...).subscribe is not a function
Solution for Issue 2:
Ensure that the mockDishService.getDishes() returns value of Observable<Menu[]> or Observable<any[]> type to match with real dishService.getDishes().
import { of } from 'rxjs';
const mockDishService = {
getDishes: () => {
return of([
{
id: '000',
name: 'nnnnn',
},
]);
},
};
Sample Solution on StackBlitz

Related

How to read subscribe in Angular Unit Test?

I am trying to write test cases of a component where at first I tried to check if a basic test case is working or not. There I encountered some errors related to Dependency Injection and solved those. Now the first issue that I am facing is mocking the API calls.
Below is my component code for which I am writing test cases:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { HttpClientService } from '#service/http-client.service';
import { CustomErrorStateMatcher } from '#validator/error-state-matcher';
import { ToastrService } from 'ngx-toastr';
#Component({
selector: 'app-prep-card',
templateUrl: './prep-card.component.html',
styles: ['legend { width: fit-content !important; }']
})
export class PrepCardComponent implements OnInit {
constructor(private fb: FormBuilder, private _http: HttpClientService, private toastr: ToastrService) { }
foamTypeList: string[] = [];
colorList: string[] = [];
ngOnInit() { this.getFoam_ColorList() }
private getFoam_ColorList() {
this._http.getFoamType_ColorList('ABC').subscribe(response => {
this.foamTypeList = response.data.foamTypesAndColors.foamTypes;
this.colorList = response.data.foamTypesAndColors.colors;
});
}
}
At first, I tried to run a simple test case to check if it is working correctly or not. Below is the test case I wrote:
import { ComponentFixture, inject, TestBed } from "#angular/core/testing";
import { FormsModule, ReactiveFormsModule } from "#angular/forms";
import { RouterTestingModule } from '#angular/router/testing';
import { HttpClientService } from "#service/http-client.service";
import { ToastrService } from "ngx-toastr";
import { MaterialModule } from "src/app/material/material.module";
import { PrepCardComponent } from "./prep-card.component";
describe('PrepCardComponent', () => {
let component: PrepCardComponent, fixture: ComponentFixture<PrepCardComponent>,
_httpSpy: jasmine.SpyObj<HttpClientService>, _toastrSpy: jasmine.SpyObj<ToastrService>;
beforeEach(async () => {
const _httpSpyObj = jasmine.createSpyObj('HttpClientService', ['getFoamType_ColorList']),
_toastrSpyObj = jasmine.createSpyObj('ToastrService', ['success', 'error']);
await TestBed.configureTestingModule({
declarations: [PrepCardComponent],
imports: [
RouterTestingModule, FormsModule, ReactiveFormsModule, MaterialModule
],
providers: [
{ provide: HttpClientService, useValue: _httpSpyObj },
{ provide: ToastrService, useValue: _toastrSpyObj },
]
}).compileComponents();
fixture = TestBed.createComponent(PrepCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('test', () => expect('a').toBe('a'));
});
The above code snippet threw the following error:
TypeError: Cannot read properties of undefined (reading 'subscribe')
at PrepCardComponent.getFoam_ColorList (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:57:52)
at PrepCardComponent.setFormFieldValidator (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:65:10)
at PrepCardComponent.createForm (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:48:10)
at PrepCardComponent.ngOnInit (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:28:10)
at callHook (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2542:1)
at callHooks (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2511:1)
at executeInitAndCheckHooks (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2462:1)
at refreshView (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:9499:1)
at renderComponentOrTemplate (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:9598:1)
at tickRootContext (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:10829:1)
To solve this, I searched different questions here and saw common solution mentioned below to get an observable.
it('Call Service', inject([HttpClientService], (_http: HttpClientService) => {
spyOn(_http, 'getFoamType_ColorList').and.returnValue({subscribe: () => {}})
}));
Writing the above test case was throwing an error (mentioned below) in the subscribe position.
Type 'void' is not assignable to type 'Subscription'.ts(2322)
Service code
getFoamType_ColorList(cardType: string) {
return this.http.get<{ message: string, data: { foamTypesAndColors: { foamTypes: string[], colors: string[] } } }>
(`${this.URL}/validate/foam-type-and-color/${cardType}`);
}
Can anyone help me out with how I can solve this issue?
UPDATE
As per dmance's answer am not getting any error while writing the test case but the test cases are still failing giving the same error. For reference refer below the full error log:
I will suggest this:
import { of } from 'rxjs';
spyOn(httpclientservice, 'getFoamType_ColorList').and.returnValue(of(YOUR VALUE));
This is a more complete answer:
describe('PrepCardComponent', () => {
let component: PrepCardComponent, fixture: ComponentFixture<PrepCardComponent>;
let httpClientService: HttpClientService;
let toastService: ToastrService;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [PrepCardComponent],
imports: [
RouterTestingModule, FormsModule, ReactiveFormsModule, MaterialModule
]
}).compileComponents();
httpClientService = TestBed.inject(HttpClientService);
toastService= TestBed.inject(ToastrService);
fixture = TestBed.createComponent(PrepCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('test', () => {
spyOn(httpClientService, 'getFoamType_ColorList').then.returnValue(of(YOUR VALUE));
// MAKE YOUR TEST
});
});
Try this maybe
spyOn(_http,'getFoamType_ColorList').and.returnValue(Observable.of(Your_Value));

Angular Karma - Component undefined

I'm trying to unit test a component that requires a Resolver, Router and ActivatedRoute as dependencies. I've tried to use the RouterTestingModule and mock my resolver to provide them in the testing module, but it seems to have some side effects on the creation of the component instance.
Here is the code of my component:
History.component.ts
import { Component, OnDestroy, OnInit } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { Subscription } from 'rxjs';
import { Transaction } from '../models/transaction.model';
#Component({
selector: 'app-history',
templateUrl: './history.component.html',
styleUrls: ['./history.component.scss']
})
export class HistoryComponent implements OnInit, OnDestroy {
history: Transaction[] = [];
selectedTransaction: Transaction | undefined;
subscription: Subscription = new Subscription();
constructor(
private route: ActivatedRoute,
private router: Router,
) { }
ngOnInit(): void {
this.history = this.route.snapshot.data.history;
const routeSubscription = this.route.params.subscribe((params) => {
if (params.id) {
this.setSelectedTransaction(+params.id);
}
});
this.subscription.add(routeSubscription);
}
setSelectedTransaction(transactionId: number): void {
const historyTransaction = this.history.find((transaction) => transaction.id === transactionId);
this.selectedTransaction = historyTransaction;
}
displayTransaction(transaction: Transaction): void {
this.router.navigate(['transactions', transaction.id]);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
And here is the current unit test:
History.spec.ts
import { ComponentFixture, TestBed } from '#angular/core/testing';
import { ActivatedRoute, Resolve, Routes } from '#angular/router';
import { RouterTestingModule } from '#angular/router/testing';
import { Observable, of } from 'rxjs';
import { Transaction } from '../models/transaction.model';
import { HistoryComponent } from './history.component';
import { HistoryResolver } from './history.resolver';
const mockRawTransactions = [
{
"id":"1",
"created_at":"2016-01-01T08:30:39-0300",
"counterparty_name":"Uber",
"debit":"false",
"credit":"true",
"amount":"44.20",
"currency":"EUR",
"operation_type":"refund",
"attachements":[
{
"url":"https:\/\/fakeimg.pl\/350x200\/?text=Hello"
}
],
}
];
const mockTransactions = mockRawTransactions.map((transaction) => new Transaction(transaction));
class HistoryMockResolver implements Resolve<Transaction[]> {
resolve(): Observable<Transaction[]> {
return of(mockTransactions);
}
}
describe('HistoryComponent', () => {
const historyRoutes: Routes = [
{ path: 'transactions', component: HistoryComponent },
{ path: 'transactions/:id', component: HistoryComponent },
];
let component: HistoryComponent;
let fixture: ComponentFixture<HistoryComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ HistoryComponent ],
imports: [
RouterTestingModule.withRoutes(historyRoutes),
],
providers: [
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params: { id: 1 },
},
},
},
{ provide: HistoryResolver, useClass: HistoryMockResolver },
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HistoryComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
console.log('Component', component);
expect(component).toBeTruthy();
});
it('should display transactions', () => {
component.history = mockTransactions;
expect(component.history).toBeDefined();
expect(component.history).toHaveSize(mockRawTransactions.length);
});
it('should display a single transaction', () => {
component.history = mockTransactions;
component.displayTransaction(component.history[0]);
expect(component.selectedTransaction).toBeDefined();
expect(component.selectedTransaction).toEqual(component.history[0]);
});
});
The component is defined and well displayed in the console.log while running the tests in Karma, but Karma raises errors for each test case and evaluates the component as undefined.
Here is the first error:
TypeError: Cannot read property 'history' of undefined
at HistoryComponent.ngOnInit (http://localhost:9876/_karma_webpack_/webpack:/src/app/history/history.component.ts:22:45)
at callHook (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:2486:1)
at callHooks (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:2457:1)
at executeInitAndCheckHooks (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:2408:1)
at refreshView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:9207:1)
at renderComponentOrTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:9306:1)
at tickRootContext (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:10532:1)
at detectChangesInRootView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:10557:1)
at RootViewRef.detectChanges (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:22569:1)
at ComponentFixture._tick (http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/core/__ivy_ngcc__/fesm2015/testing.js:141:1)
What should I fix in my testing module ?
This is because of this.route.snapshot.data.history and data being undefined as your have not passed it in your mock activated snapshot.
You can update your provider for activated route snapshot in History.spec.ts
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params: { id: 1 },
data: {history: 'something-history-obj'}
},
},
},
Or you can always use this.route.snapshot.data?.history within History.component.ts if it is indeed nullable

Angular2 unit test. Check if a function calls router.navigate

I'm new to testing. Have a function that, when it's called, navigates to a new page. But the test is failing with an error:
Expected spy navigate to have been called with [ [
'./../admin/documents/12345' ] ] but it was never called.
public showProfile(id) {
this.router.navigate(['./../admin/documents/' + id]);
}
In my test file I have:
import {ComponentFixture, TestBed, fakeAsync, tick } from '#angular/core/testing';
import { AppComponent} from './app.component';
import {FormsModule} from "#angular/forms";
import {HttpClientTestingModule} from "#angular/common/http/testing";
import {Router} from "#angular/router";
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let mockRouter;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent],
imports: [FormsModule, HttpClientTestingModule],
providers: [
{ provide: Router, useValue: mockRouter }]
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
mockRouter = {
navigate: jasmine.createSpy('navigate')
};
});
describe('when showProfile() is called', () => {
it('navigates to a profile page',() => {
const id= 12345;
component.showProfile(id);
expect(mockRouter.navigate)
.toHaveBeenCalledWith(['./../admin/documents/' + id]);
});
});
});
You need to initialize the mockRouter before you use it in TestBed.configureTestingModule.
Also, expect(mockRouter.navigate).toHaveBeenCalledWith(['./../admin/documents/' + id]); won't work because ['a'] !== ['a']. As a workaround, you can do something like:
expect(mockRouter.navigate.calls.mostRecent().args[0][0])
.toEqual('./../admin/documents/' + id);
I've created a Stackblitz for your test.

Cannot read property 'length' of null + "angular"?

I am trying to count initial li and after fetching data from server (using unit test case), but I am getting Cannot read property 'length' of null
My code:
import { ComponentFixture, TestBed, async, getTestBed } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { MockAppService } from './mock.service'
import { DebugElement } from '#angular/core';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>,
component: AppComponent,
service: AppService,
debugEl:DebugElement,
el:HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [
AppComponent
],
providers: [{ provide: AppService, useClass: MockAppService }]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
service = TestBed.get(AppService);
el = fixture.nativeElement;
spyOn(service, 'getData').and.callThrough();
}));
afterEach(() => {
//httpMock.verify();
});
describe('AppComponent onit test', () => {
it('intial list item', async(() => {
debugEl = fixture.debugElement.query(By.css('li'));
expect(fixture.nativeElement.querySelector('li').length()).toBe(0);
}));
it('should called appService getData method', async(() => {
fixture.detectChanges();
expect(service.getData).toHaveBeenCalled();
}));
it('should return an Observable<User[]>', () => {
const dummyUsers = [{
userId: 10,
id: 10,
title: "post",
body: "post"
}];
service.getData().subscribe(users => {
console.log(users)
expect(users.length).toBe(1);
expect(users).toEqual(dummyUsers);
expect(fixture.nativeElement.querySelector('li').length()).toBe(1);
});
});
})
});
code link
https://stackblitz.com/edit/angular-testing-w9towo?file=app%2Fapp.component.spec.ts
query does not return an array, try to use queryAll to return an array instead of query
here is the solution:
it('intial list item', async(() => {
let liCount= fixture.debugElement.queryAll(By.css('li'));
expect(liCount.length).toBe(0);
}));
When you look at this documentation: https://angular.io/api/core/DebugElement
You will find that DebugElement.query method returns DebugElement
and the method DebugElement.queryAll method returns DebugElement[]
so DebugElement.queryAll will return an array of DebugElement
and in this case, since it's an array you can then apply length property to it.
So you have to use DebugElement.queryAll in order to test the length of the resulting array.

how to check function is called or not in angular?

I am trying to test component in angular .following thing I need to test
service function is called or not
how to mock the response
here is my code
https://stackblitz.com/edit/angular-testing-w9towo?file=app%2Fapp.component.spec.ts
spec.ts
import { ComponentFixture,TestBed, async,getTestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
describe('AppComponent', () => {
let fixture:ComponentFixture<AppComponent>,
component:AppComponent,
injector:TestBed,
service:AppService,
httpMock:HttpTestingController,
el:HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [
AppComponent
],
providers: [ AppService ]
}).compileComponents();
}));
afterEach(() => {
//httpMock.verify();
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
// injector = getTestBed();
// service = injector.get(AppService);
// httpMock = injector.get(HttpTestingController);
spyOn('appService',getData);
describe('AppComponent onit test', () => {
it('should create the app', async(() => {
expect(true).toBe(true);
}));
it('should called appService getData method', async(() => {
expect(appService.getData).toHaveBeenCalled();
}));
})
});
getting error
cannot read property 'injector' of null
you can mock the service that way:
const mockPosts: Posts = {
userId: 10,
id: 10,
title: "post",
body: "post"};
class MockAppService extends AppService{
public getData() {
return Observable.of(mockPosts)
}
}
and use that mock class in your providers instead of the service
{ provide: AppService, useClass: MockAppService },
and add this:
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
appservice = TestBed.get(AppService); // this line
you can spyOn that service and return a value like this
spyOn(appservice , 'getData').and.returnValue("your value")
final file
import { ComponentFixture,TestBed, async,getTestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
import { Observable } from 'rxjs/Observable';
import { Posts } from './post.interface';
import 'rxjs/add/observable/of';
const mockPosts: Posts =
{userId: 10,
id: 10,
title: "post",
body: "post",};
class MockAppService extends AppService {
public getData(){
return Observable.of(mockPosts)
}
}
describe('AppComponent', () => {
let fixture:ComponentFixture<AppComponent>,
component:AppComponent,
injector:TestBed,
service:AppService,
httpMock:HttpTestingController,
el:HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [
AppComponent
],
providers: [
{ provide: AppService, useClass: MockAppService }
]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
service = TestBed.get(AppService)
// injector = getTestBed();
// service = injector.get(AppService);
// httpMock = injector.get(HttpTestingController);
spyOn(service,'getData');
}));
afterEach(() => {
//httpMock.verify();
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
service = TestBed.get(AppService)
// injector = getTestBed();
// service = injector.get(AppService);
// httpMock = injector.get(HttpTestingController);
spyOn(service,'getData');
describe('AppComponent onit test', () => {
it('should create the app', async(() => {
expect(true).toBe(true);
}));
it('should called appService getData method', async(() => {
fixture.detectChanges();
expect(service.getData).toHaveBeenCalled();
}));
})
});

Categories