Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - how to check function is called or not in angular?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
  }));
  })
 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...