Wednesday, June 19, 2019

How to do testing of Method in Service.spec.ts file

Let say you have following code written in DataAccessService
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataAccessService {
constructor(private client: HttpClient) { }
getData() {
return this.client.get('https://jsonplaceholder.typicode.com/todos/2');
}
}
In this case you must have following data-access.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { DataAccessService } from './data-access.service';
import { Post } from './models/post.model';
describe('DataAccessService', () => {
let service: DataAccessService;
let myArrayData = [];
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [DataAccessService]
});
service = TestBed.get(DataAccessService);
});
it('be able to retrieve posts from the API bia GET', (done: DoneFn) => {
const dummyPosts: Post[] = [{
userId: '1',
id: '1',
title: 'delectus aut autem1',
completed: 'false'
}];
service.getData().subscribe(posts => {
//expect(posts.length).toBe(1);
myArrayData = Object.values(posts);
console.log("-------posts------" + Object.values(posts));
console.log("-------myArrayData------" + myArrayData[2]);
// tslint:disable-next-line:forin
for (var key in dummyPosts) {
if (dummyPosts.hasOwnProperty(key)) {
console.log('key---------------------' + key);
console.log(dummyPosts[key].title);
}
expect(myArrayData[2]).toMatch(dummyPosts[key].title);
done();
}
});
});
})
Image8

Change title: 'quis ut nam facilis et officia qui' in the above code and rerun the test

Image9Image10

No comments: