如何在角度中调用或不调用函数?

时间:2018-04-15 12:30:23

标签: javascript angular unit-testing

我正在尝试在角色中测试component。我需要测试

  1. 是否调用服务功能
  2. 如何模拟回复
  3. 这是我的代码 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();
      }));
    })
    });
    

    收到错误 无法读取null的属性'injector'

1 个答案:

答案 0 :(得分:4)

您可以通过这种方式模拟服务:

const mockPosts: Posts = {
   userId: 10,
   id: 10,
   title: "post",
   body: "post"};

class MockAppService extends AppService{

   public getData() {
      return Observable.of(mockPosts)
   }
  }

并在您的提供者中使用该模拟类而不是服务

 { provide: AppService, useClass: MockAppService },

并添加:

 fixture = TestBed.createComponent(AppComponent);
 component = fixture.componentInstance;
 appservice = TestBed.get(AppService); // this line

你可以窥探该服务并返回一个像这样的值

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