Unit test(二)spynOn service

 1.angular 中普通service在unit test中的例子.

 

  import 导入-----> 声明----->TestBed.config providers------->BeforeEach中TestBed.get创造------>在测试用例中spyOn使用

 2.ActivatedRoute在unit test中例子

   源ts文件

this.route.queryParams.pipe(
      map(params => params),
      mergeMap((data: any) => {
        const code = data.code;
        const state = data.state;
        if (state !== this.envService.config.state) {
          return Observable.throw('Wrong state...');
        }
        const redirectUri = window.location.origin + this.envService.config.redirect_uri;
        return this.apiService.authenticate(code, this.envService.config.client_id, redirectUri);
    })).subscribe(()=>......)

 针对的测试套件

//它是通过在TestBed中注入fake AcitivatedRoute来实现的
//首先创建一个fake函数(项目中我是直接使用of来创建Oberserable的)其他的例子
//snapshot fake
describe('SomeComponent', () => {

  const fakeActivatedRoute = {
    snapshot: { data: { ... } }
  } as ActivatedRoute;

  beforeEach(async(() => {
    TestBed.configureTestingModule({ 
      imports: [ RouterTestingModule ],
      declarations: [ SomeComponent ],
      providers: [ {provide: ActivatedRoute, useValue: fakeActivatedRoute} ],
    })
    .compileComponents();
  }));
});
// queryParams fake
describe('SomeComponent', () => {
  let mockUrlParams = {
        code: "XXjaQnpWHbelDbB51SSxGBgToYKedVGWXPOayu9gvLAZI5NOcCVi9i15LT0IzsQD",
    state: "vmcu-est-app"
  }

  
  beforeEach(async(() => {
    TestBed.configureTestingModule({ 
      imports: [ RouterTestingModule ],
      declarations: [ SomeComponent ],
           { provide: ActivatedRoute, useValue: { queryParams: of(mockUrlParams) } },
    })
    .compileComponents();
  }));
});

  

 3.Router 跳转在unit test中的例子

 

//原文档

if (this.customer.length == 0) {
     this.router.navigate(['/nocustomer']);
 } 

//使用 jasmine.createSpy 来处理
//先创建一个变量作为mockSpy

  let routerSpy = { navigate: jasmine.createSpy('navigate') };

//再把mockSpy 加入TestBed

TestBed.configureTestingModule({
  providers: [
    { provide: Router, useValue: routerSpy }
  ]
})

//最后可以使用routeSpy来断言

it(`should navigate to nocustomer`, () => {
   component.customers = [];
   expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
});

  

 4.测试用例中service的函数spyOn的简单用法:1.直接spyOn;2TestBed前注入,利用jamine.createSpy

4.1 直接使用spyOn

  it('should create', () => {
    spyOn(apiService, 'authenticate').and.returnValue(of(mockToken));
    expect(component).toBeTruthy();
  });

 spyOn(foo, "getBar").and.callFake(function() {
                return 1001;
            });

4.2 jamine.createSpy

 let userServiceSpy = {
    logout: jasmine.createSpy('logout', function () { console.log('logout') }),
    saveCurrentSession: jasmine.createSpy('saveCurrentSession', function () { console.log('saveCurrentSession') }),
    setFeedBackUser: jasmine.createSpy('setFeedBackUser', function () { console.log('setFeedBackUser') })
  };
TestBed.configureTestingModule({
      declarations: [LoginComponent],
      providers: [
        UserService,
        { provide: UserService, useValue: userServiceSpy }
      ]
 })
      .compileComponents();
  });

  

  成例:login-spec.ts

import { HttpClientModule } from '@angular/common/http';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute, RouterModule, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { NgxsModule } from '@ngxs/store';
import { ApiService } from 'src/app/services/api.service';
import { EnvironmentsService } from 'src/app/services/environment.service';
import { UserService } from 'src/app/services/user.service';


import { LoginComponent } from './login.component';

import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ClarityModule } from '@clr/angular';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgxsFormPluginModule } from '@ngxs/form-plugin';
import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin';
import { AppRoutingModule } from '../../app-routing.module';

describe('LoginComponent', () => {
  let mockUrlParams = {
    code: "XXjaQnpWHbelDbB51SSxGBgToYKedVGWXPOayu9gvLAZI5NOcCVi9i15LT0IzsQD",
    state: "vmcu-est-app"
  }

  let mockToken = { "access_token": "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXNwLXN0YWdpbmcudm13YXJlLWF3cy5jb20iLCJzdWIiOiJ5YW5ncSIsInByb3ZpZGVyIjoid29ya3NwYWNlX29uZSIsImVtYWlsIjoieWFuZ3FAdm13YXJlLmNvbSIsIm5hbWUiOiJRaW5nIFlhbmciLCJ1c2VybmFtZSI6InlhbmdxIiwiY29tcGFueV9uYW1lIjoiVk13YXJlLCBJbmMuIiwiY2xpZW50X2lkIjoiZXNwLXN0Zy00NjUtYXlidHIiLCJpYXQiOjE2Mjg2NTA3NzgsImV4cCI6MTYyODY1MjU3OH0.GwFGzcT3MSAGUtzBTMsrZNyIpw827TejxKOOLXxSlMnuSKQXo9R59XuFqMeZwelBkoy0i7j1IWb36azaW6s40dEfZ3Hp-DdxA0F_nZn5nT4vDHxA-dK0zxgaWqazgb_D0FzweIuPmYPMgG_1WlnIM0FA0t-lHaUsrTjUKBKJ3aM1cWk5FJ6FMysjVAo9ym0VuVsWGOa1P5KaCD_AWks9LGGT6evctWOswKhYlGjcyYWmd-ixz4MI5uWtIeQGeXf4cCzOKkd5sP3vlgTkAjaSk1NWSz15pFVqBLdBo5gDG-mX-JqIWR-J8mcTk_byikUU0MZzQcHGhiWJiinDET_JQg", "access_type": "bearer", "expires_in": 1800, "refresh_token": "vNooevvg6Dd1wE6BhWmXKifGPBkb5AMUGLLGSnzgoXxoF2JCYoyZ8Uo0smcpm6LG" }

  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let apiService: ApiService;
  let userService: UserService;
  let routerSpy = { navigate: jasmine.createSpy('navigate') };
  let userServiceSpy = {
    logout: jasmine.createSpy('logout', function () { console.log('logout') }),
    saveCurrentSession: jasmine.createSpy('saveCurrentSession', function () { console.log('saveCurrentSession') }),
    setFeedBackUser: jasmine.createSpy('setFeedBackUser', function () { console.log('setFeedBackUser') })
  };

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [LoginComponent],
      providers: [
        ApiService,
        EnvironmentsService,
        UserService,
        { provide: ActivatedRoute, useValue: { queryParams: of(mockUrlParams) } },
        { provide: Router, useValue: routerSpy },
        { provide: UserService, useValue: userServiceSpy }
      ],
      imports: [
        CommonModule,
        BrowserModule,
        ClarityModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        HttpClientModule,
        NgxsFormPluginModule.forRoot(),
        NgxsReduxDevtoolsPluginModule.forRoot(),
        NgxsModule,
        RouterModule
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    apiService = TestBed.get(ApiService);
    userService = TestBed.get(UserService);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    spyOn(apiService, 'authenticate').and.returnValue(of(mockToken));
    expect(component).toBeTruthy();
  });

  it("ngOnInit", () => {
    spyOn(apiService, 'authenticate').and.returnValue(of(mockToken));
    component.ngOnInit();
    expect(apiService.authenticate).toHaveBeenCalled()
  })
});

  

 参考:

   1.Jasmine入门(结合实例详解)

 2.how to unit test router.navigate in angular app

   3.Angular 4 - Failed: Can't resolve all parameters for ActivatedRoute: (?, ?, ?, ?, ?, ?, ?, ?)

原文地址:https://www.cnblogs.com/rushintocloud/p/15127321.html