4

I am trying to test component in angular .following thing I need to test

  1. service function is called or not
  2. 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

1 Answer 1

4

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();
  }));
  })
 });
Sign up to request clarification or add additional context in comments.

7 Comments

i don't know why i'm not able to share it but i updated the answer with the final file, check it
still I am getting error stackblitz.com/edit/…
could you please look once again
i've edited the answer , you have to put this code inside beforeeach after compiling , fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; service = TestBed.get(AppService) // injector = getTestBed(); // service = injector.get(AppService); // httpMock = injector.get(HttpTestingController); spyOn(service,'getData');
i've added import 'rxjs/add/observable/of'; and i added fixture.detectChanges() here, it('should called appService getData method', async(() => { fixture.detectChanges(); expect(service.getData).toHaveBeenCalled(); }));
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.