如何对Angular解析器的可选路由参数进行单元测试

时间:2019-08-12 15:02:03

标签: angular unit-testing angular-router

我正在尝试对Angular 7解析器的可选路由参数进行单元测试,但只有在提供参数后才能使其正常工作。

下面的代码可以正常工作,但是我想测试一个没有提供ID的情况(用户导航到incident,而不是incident/12345

如何在单元测试中实现这一目标?

我的路由在我的路由模块中设置如下:

{
    path: 'incident',
    component: IncidentComponent,
    resolve: {
        rescue: RescueResolver
    }
},
{
    path: 'incident/:id',
    component: IncidentComponent,
    resolve: {
        rescue: RescueResolver
    }
},
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { async, TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap } from '@angular/router';

import { RescueResolver } from '@core/resolvers';
import { RescueService } from '@core/services';

fdescribe('RescueResolver', () => {
    let resolver: RescueResolver;
    let service: RescueService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                RescueResolver,
                RescueService,
                {
                    provide: ActivatedRoute,
                    useValue: {
                        snapshot: {
                            paramMap: convertToParamMap({
                                id: '1'
                            })
                        }
                    }
                }
            ]
        });
    }));

    beforeEach(async(() => {
        resolver = TestBed.get(RescueResolver);
        service = TestBed.get(RescueService);
    }));

    it('should be defined', () => {
        expect(resolver).toBeDefined();
    });

    it('should call getRescue when an id has been passed as a parameter', () => {
        spyOn(service, 'getRescue');
        resolver.resolve();
        expect(service.getRescue).toHaveBeenCalledWith('1');
    });
});

0 个答案:

没有答案