Angular 如何编写解析测试

Angular 如何编写解析测试,angular,typescript,testbed,Angular,Typescript,Testbed,我想为我的服务编写测试, 我想确定参数是否发送正常。如何测试该参数 import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { JhiPaginationUtil } from '.'; @Injectable() export class JhiResolvePagingP

我想为我的服务编写测试, 我想确定参数是否发送正常。如何测试该参数

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { JhiPaginationUtil } from '.';

@Injectable()
export class JhiResolvePagingParams implements Resolve<any> {

    constructor(private paginationUtil: JhiPaginationUtil) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const page = route.queryParams['page'] ? route.queryParams['page'] : '1';
        const defaultSort = route.data['defaultSort'] ? route.data['defaultSort'] : 'id,asc';
        const sort = route.queryParams['sort'] ? route.queryParams['sort'] : defaultSort;
        return {
            page: this.paginationUtil.parsePage(page),
            predicate: this.paginationUtil.parsePredicate(sort),
            ascending: this.paginationUtil.parseAscending(sort)
        };
    }
}
从'@angular/core'导入{Injectable};
从'@angular/router'导入{Resolve,ActivatedRouteSnapshot,RouterStateSnashot};
从“.”导入{JhiPaginationUtil};
@可注射()
导出类JhiResolvePagingParams实现解析{
构造函数(私有分页直到:JhiPaginationUtil){}
解析(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot){
const page=route.queryParams['page']?route.queryParams['page']:'1';
const defaultSort=route.data['defaultSort']?route.data['defaultSort']:'id,asc';
const sort=route.queryParams['sort']?route.queryParams['sort']:defaultSort;
返回{
页面:this.paginationUtil.parsePage(第页),
谓词:this.paginationUtil.parsePredicate(排序),
升序:this.paginationUtil.parseAscending(排序)
};
}
}

您需要为每个测试用例创建一个假的
ActivatedRoute
,并将其传递给
resolver.resolve()
方法。大概是这样的:

import { JhiResolvePagingParams, JhiPaginationUtil } from '../..';
import { ActivatedRouteSnapshot } from '@angular/router';
import { TestBed, inject } from '@angular/core/testing';

describe('ResolvePagingParams  service test', () => {

    describe('ResolvePagingParams Links Service Test', () => {
        let resolver: JhiResolvePagingParams;
        let route: ActivatedRouteSnapshot;

        beforeEach(() => {
            resolver = new JhiResolvePagingParams(new JhiPaginationUtil());
            route = new ActivatedRouteSnapshot();
            TestBed.configureTestingModule({
                providers: [
                    JhiResolvePagingParams,
                    JhiPaginationUtil
                ]
            });
        });

        it(`should return { page: 1, predicate: 'id',ascending: true } when page and sort and defaultSort is undefined` ,
            inject([JhiResolvePagingParams], (service: JhiResolvePagingParams) => {
            route.queryParams = { page: undefined, sort: undefined };
            route.data = { defaultSort: undefined };
            const { page, predicate, ascending } = resolver.resolve(route, null);

            expect(page).toEqual(1);
            expect(predicate).toEqual('id');
            expect(ascending).toEqual(true);
        }));

    });
});

角度为8/9时:

现在您使用
Testbed.inject([YourComponent/Service])
而不是
Testbed.get([YourComponent/Service])
,还需要在
@Injectable
注释上定义在:'root'属性中提供的
。如果您正在使用angular服务获取数据,那么这可以帮助您了解如何测试是否创建了解析器:

这是我要测试的解析器的单元测试:

describe('TagResolver', () => {
let resolver: TagResolver;

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [
      HttpClientTestingModule
    ],
    providers: [

    ]
  });
  resolver = TestBed.inject(TagResolver);
});

it('should create an instance', () => {
    expect(resolver).toBeTruthy();
  });
});
这是解析程序:

@Injectable({
  providedIn: 'root'
})
export class TagResolver implements Resolve <Observable<Tag[]>> {

  constructor(private readonly refTagService: RefTagsService) {
  }
  resolve(route: ActivatedRouteSnapshot,
          state: RouterStateSnapshot):
          Observable<any[]> |
          Observable<Observable<any[]>> |
          Promise<Observable<any[]>> {
    return this.refTagService.getRefTags();
  }
}
@可注入({
providedIn:'根'
})
导出类TagResolver实现解析{
构造函数(专用只读引用标记服务:引用标记服务){
}
解析(路由:ActivatedRouteSnapshot,
状态:路由器状态(快照):
可观察|
可观察|
允诺{
返回此.refTagService.getRefTags();
}
}
最后,这是解析器从中获取数据的服务:

@Injectable({
  providedIn: 'root'
})
export class RefTagsService {
  refTagsEndPoint = '/api/tags';
  constructor(private readonly http: HttpClient) { }

  getRefTags(): Observable<Tag[]> {
    console.log('getRefTags');
    return this.http.get<Tag[]>(`${this.refTagsEndPoint}`).pipe(
      map(res => {
        return res;
      })
    );
  }
}
@可注入({
providedIn:'根'
})
导出类引用标记服务{
refTagsEndPoint='/api/tags';
构造函数(私有只读http:HttpClient){}
getRefTags():可观察{
log('getRefTags');
返回this.http.get(`${this.refTagsEndPoint}`).pipe(
地图(res=>{
返回res;
})
);
}
}

解析路径前测试令牌的解析程序示例:

@Injectable({
  providedIn: 'root'
})
export class JwtResolverService implements Resolve<string> {

  constructor(private authService: AuthService) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<string> {
    return this.authService.getToken()
      .pipe(
        tap(value => log.debug(`============= Resolving token: ${value} =============`)),
        catchError(err => of(null))
      );
  }

}
@可注入({
providedIn:'根'
})
导出类JwtResolverService实现解析{
构造函数(私有authService:authService){}
解析(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot):可观察{
返回这个.authService.getToken()
.烟斗(
点击(value=>log.debug(`=========================解析令牌:${value}===============================`)),
catchError(err=>of(null))
);
}
}
测试:

从'@angular/core/testing'导入{TestBed};
从“./jwt resolver.service”导入{JwtResolverService};
从'@angular/common/http/testing'导入{HttpClientTestingModule};
从'rxjs'导入{可观察的};
从“../../auth/auth.service”导入{AuthService};
从'@angular/router'导入{ActivatedRouteSnapshot};
类MockAuthService{
令牌='1234';
getToken():可观察{
归还(此令牌);
}
}
描述('JWT ResolversService',()=>{
let解析器:JwtResolverService;
让authService:authService;
let route:ActivatedRouteSnapshot;
在每个之前(()=>{
TestBed.configureTestingModule({
进口:[
HttpClientTestingModule
],
供应商:[
{提供:AuthService,useClass:MockAuthService},
]
});
路由=新的ActivatedRouteSnapshot();
authService=TestBed.inject(authService);
解析器=TestBed.inject(JwtResolverService);
});
它('应该创建',()=>{
expect(解析器).toBeTruthy();
});
它('应在令牌可用时解析',()=>{
//安排
//表演
解析(路由,空)。订阅(解析=>{
//断言
expect(已解决)。toBeTruthy();
});
})
它('当令牌不可用时不应解析',()=>{
//安排
spyOn(authService,'getToken')。和.returnValue(of(null));
//表演
解析(路由,空)。订阅(解析=>{
//断言
expect(已解决)。toBeFalsy();
});
})
它('错误时不应解决',()=>{
//安排
spyOn(authService,'getSVBToken')。和.returnValue(throwError({status:404}));
//表演
解析(路由,空)。订阅(解析=>{
//断言
expect(已解决)。toBeFalsy();
});
})
});

您创建一个ActivatedRouteSnapshot,填充它,用该路由作为参数调用resolve()方法,并检查它是否返回预期值。您能尝试一下吗?如何构造JhiPaginationUtil?我会模拟它。为JhiPaginationUtil的每个属性创建一个间谍(
parsePage
parsePredicate
parseAscending
)。然后,您可以将期望值更改为:
expect(parsePageSpy)。如果您使用
const service=TestBed.get(JhiResolvePagingParams)获取服务,则可以避免注入(…)
import { TestBed } from '@angular/core/testing';
import { JwtResolverService } from './jwt-resolver.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Observable, of } from 'rxjs';
import { AuthService } from '../../auth/auth.service';
import { ActivatedRouteSnapshot } from '@angular/router';

class MockAuthService {
  token = '1234';

  getToken(): Observable<string> {
    return of(this.token);
  }
}

describe('JWT ResolverService', () => {
  let resolver: JwtResolverService;
  let authService: AuthService;
  let route: ActivatedRouteSnapshot;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        { provide: AuthService, useClass: MockAuthService },
      ]
    });

    route = new ActivatedRouteSnapshot();
    authService = TestBed.inject(AuthService);
    resolver = TestBed.inject(JwtResolverService);
  });

  it('should be created', () => {
    expect(resolver).toBeTruthy();
  });

  it('should resolve when token is available', () => {
    // arrange

    // act
    resolver.resolve(route, null).subscribe(resolved => {
      // assert
      expect(resolved).toBeTruthy();
    });

  })

  it('should not resolve when token is not available', () => {
    // arrange
    spyOn(authService, 'getToken').and.returnValue(of(null));

    // act
    resolver.resolve(route, null).subscribe(resolved => {
      // assert
      expect(resolved).toBeFalsy();
    });

  })

  it('should not resolve on error', () => {
    // arrange
    spyOn(authService, 'getSVBToken').and.returnValue(throwError({status: 404}));

    // act
    resolver.resolve(route, null).subscribe(resolved => {
      // assert
      expect(resolved).toBeFalsy();
    });
  })
});