如何在角度中调用或不调用函数? [英] how to check function is called or not in angular?

查看:210
本文介绍了如何在角度中调用或不调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在角度中测试组件。我需要测试的东西

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


  1. 是否调用服务功能

  2. 如何模拟回复

这里是我的代码
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();
  }));
})
});

获取错误
无法读取属性'注入器'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 },

并添加:

 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")

最终文件

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

这篇关于如何在角度中调用或不调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆