How to write test for Resolve

ali akbar azizkhani picture ali akbar azizkhani · Apr 4, 2018 · Viewed 8.3k times · Source

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

Answer

Tomasz Kula picture Tomasz Kula · Apr 5, 2018

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

    });
});