4

I want to write test for my service , I want to sure parameter is send ok .how can i test that

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)
        };
    }
}
ali akbar azizkhani
  • 2,213
  • 5
  • 31
  • 48

3 Answers3

10

You need to create a fake ActivatedRoute for each of you test cases and pass it to the resolver.resolve() method. Something like this:

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

    });
});
ali akbar azizkhani
  • 2,213
  • 5
  • 31
  • 48
Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
  • 1
    How to construct JhiPaginationUtil ? – ali akbar azizkhani Apr 05 '18 at 17:49
  • I'd just mock it. Create a spy for each property of the JhiPaginationUtil (`parsePage`, `parsePredicate`, `parseAscending`). Then you can change the expectations to something like: `expect(parsePageSpy).toHaveBeenCalledWith(...)` – Tomasz Kula Apr 05 '18 at 20:05
  • If you get the service with a `const service = TestBed.get(JhiResolvePagingParams)` you can avoid the injection – David Aug 22 '19 at 12:21
3

Example resolver for testing a token before the path is resolved:

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

}

Test:

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();
    });
  })
});
Ron Jonk
  • 706
  • 6
  • 16
1

For Angular 8/9:

Now you use Testbed.inject([YourComponent/Service]) instead of TestBed.get([YourComponent/Service]), also you need to define the providedIn: 'root' property on the @Injectable annotation. And if you are using an angular service to fetch data, then this could help you to understand how to test that a Resolver was created:

This is the unit test for the resolver I want to test:

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

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

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

it('should create an instance', () => {
    expect(resolver).toBeTruthy();
  });
});

This is the resolver:

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

And last one, this is the service which the resolver fetch data from:

@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;
      })
    );
  }
}
vhbazan
  • 1,240
  • 1
  • 17
  • 26