Unit test(二)spynOn service

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

 

 

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

 2.ActivatedRoute在unit test中例子

   源ts文件

1
2
3
4
5
6
7
8
9
10
11
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(()=>......)

 针对的测试套件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//它是通过在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中的例子

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//原文档
 
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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: (?, ?, ?, ?, ?, ?, ?, ?)

posted @   两块五的菜鸟  阅读(154)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示