1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

How to mock a service that contains http request and returns an observable?

Discussão em 'Angular' iniciado por user8348978, Novembro 7, 2024 às 10:22.

  1. user8348978

    user8348978 Guest

    Below is my Service class which is taking a url which has a json format data.

    service.ts

    import { Injectable } from "@angular/core";
    import { Http } from '@angular/http';
    import { Observable } from "rxjs/Observable";

    @Injectable()

    export class Service {

    public http: string;
    constructor(private http: Http) { }

    getGoogle():Observable<any> {
    console.log("Inside service");


    return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
    }
    }


    Below is my page1.ts file which uses the service and gets the data from the service.

    page1.ts

    import { Component } from '@angular/core';
    import { Service } from "../../services/service";


    @Component({
    selector: 'page-page1',
    templateUrl: 'page1.html',
    })
    export class Page1 {

    constructor(private service: Service) {

    }

    ionViewDidLoad() {
    console.log('ionViewDidLoad Page1');
    }

    get() {
    console.log("inside get method");
    this.service.getGoogle().subscribe(
    (response:Response)=>{
    console.log('The resonse is', response);
    });
    }


    Please ignore any typo.

    Below is my spec file for this page, where I want to test this asynchronous http get method

    page1.spec.ts

    import { TestBed, async, ComponentFixture, inject } from '@angular/core/testing';
    import { Page1 } from './page1';
    import { IonicModule, NavController } from "ionic-angular";
    import { DebugElement } from "@angular/core";
    import { Service } from "../../services/service";
    import { By } from "@angular/platform-browser";


    describe('Page1 to be tested', () => {

    let fixture: ComponentFixture<Page1>;
    let comp: Page1;
    let de: DebugElement;
    let el: HTMLElement;



    beforeEach(async(() => {
    TestBed.configureTestingModule({
    declarations: [Page1],
    imports: [
    IonicModule.forRoot(Page1),

    ],
    providers: [NavController,
    //need to provide service I have already imported it.

    ],
    }).compileComponents();

    }

    ));
    beforeEach(() => {
    fixture = TestBed.createComponent(Page1);
    comp = fixture.componentInstance;
    de = fixture.debugElement;

    });

    afterEach(()=>{
    fixture.destroy();
    })

    it('is created', () => {
    expect(comp).toBeTruthy();
    expect(fixture).toBeDefined();
    });

    it('Testing the service', ()=>{
    //testing service.
    })


    });


    Note: I have to create a mock for this service, based on the real service that I have used.I am not sure whether this mock is correct.Please have a look at this mock.The data provided in the get url in this mock is in another folder which is named as data.mock.ts.

    service.mock.ts

    import { Observable } from 'rxjs/Observable';
    import { Http } from '@angular/http';
    import 'rxjs/add/operator/map';

    export class ServiceMock {
    public http: Http;
    url: string;
    getGoogle(): Observable<any> {
    return this.http.get('./data.mock').map((res) => {
    res.json();
    });
    }
    }


    data.mock.ts

    export class Data {
    name: string = 'Aditya';
    profession: string = 'Developer';
    }

    Continue reading...

Compartilhe esta Página