简体   繁体   English

如何对使用router.paramMap的Angular 4组件进行单元测试

[英]How to unit test a Angular 4 component which uses router.paramMap

I m new to angular 4 and trying to test one of the angular 4 feature router.paramMap from unit tests, Reading route params in fallowing way and working as expected in my application. 我是角度4的新手,试图从单元测试中测试一个角度4特征router.paramMap,以下面的方式读取路径参数并在我的应用程序中按预期工作。

constructor(private router:Router, private actRoute:ActivatedRoute) {
}

ngOnInit() {
    this.router.paramMap.subscribe(params => {
        params.get(id);
    })
......
}

But while running unit test, im getting error which says cannot call subscribe method of undefined even though im passing passing route param as below. 但是在运行单元测试的时候,即使我通过传递路径参数,我也得到了不能调用未定义的订阅方法的错误。

{
  provide: ActivatedRoute,
  useValue: { params: Observable.of({id: 1}) }
}

Please suggest 请建议

You need to provide paramMap instead of params . 你需要提供paramMap而不是params paramMap should be of type ParamMap from @angular/router , so normal object can be converted to ParamMap using the method convertToParamMap() from @angular/routing . paramMap应该是来自@angular/router ParamMap类型,因此可以使用@angular/routing convertToParamMap()方法将普通对象转换为ParamMap

You can provide the mock ActivatedRoute like below: 您可以提供如下的模拟ActivatedRoute:

import { convertToParamMap} from '@angular/router';
....
.....

{
      provide: ActivatedRoute,
      useValue: { paramMap: Observable.of(convertToParamMap({id: 1})) }
}

I am using a slightly different method of getting the params in my component: 我使用一种稍微不同的方法来获取组件中的参数:

this.id = this.route.snapshot.paramMap.get('id');

And this is what worked for me in the jasmine test: 这对茉莉花测试有用:

{
      provide: ActivatedRoute,
      useValue: {
        snapshot: {
          paramMap: convertToParamMap({id: 1})
        }
      }
}

我们目前正在使用这个:

    { provide: ActivatedRoute, useValue: { 'params': Observable.from([{ 'id': '1'}]) } },

Your code has a problem, in order to get a param from the URL, you have to write things in a different way. 您的代码有问题,为了从URL获取参数,您必须以不同的方式编写内容。

constructor(private router:Router, private actRoute:ActivatedRoute) {
}

ngOnInit() {
    this.router.paramMap
        .switchMap((params: ParamMap) => {
            params.get(id);
            ....
        })
        .subscribe((....) => {
            ....
        })
}

For anyone needing tests on a component for when it does have a certain route param, and when it does not have it (as in /product and /product/:id ), the following works for me: 对于任何需要对某个组件进行测试的人,如果它确实有某个路由参数,并且没有它(如/product/product/:id ),则以下内容适用于我:

The component: 组件:

export class PageProductComponent implements OnInit {
    id: string | null = null;

    constructor(private readonly activatedRoute: ActivatedRoute) { }

    ngOnInit(): void {
        this.id = this.activatedRoute.snapshot.paramMap.get('id');
    }
}

The tests: 测试:

describe('PageProductComponent ', () => {
    let component: PageProductComponent ;
    let fixture: ComponentFixture<PageProductComponent >;
    let debugEl: DebugElement;

    const makeCompiledTestBed = (provider?: object): void => {
        const moduleDef: TestModuleMetadata = {
            imports: [
                RouterTestingModule,
            ],
            declarations: [ PageProductComponent ],
            providers: [ ]
        };
        if (moduleDef.providers && provider) {
            moduleDef.providers.push(provider);
        }
        TestBed.configureTestingModule(moduleDef).compileComponents();
    };

    const setupTestVars = (): void => {
        fixture = TestBed.createComponent(PageProductComponent );
        component = fixture.componentInstance;
        debugEl = fixture.debugElement;
        fixture.detectChanges();
    };

    describe('When an ID is NOT provided in the URL param', () => {
        beforeEach(async(makeCompiledTestBed));
        beforeEach(setupTestVars);

        it('should list all products', () => {
            //...
        });

    });

    describe('When an ID is provided in the URL param', () => {
        beforeEach(async(() => {
            makeCompiledTestBed({
                provide: ActivatedRoute,
                useValue: {
                    snapshot: {
                        paramMap: convertToParamMap({id: 1234})
                    }
                }
            });
        }));

        beforeEach(setupTestVars);

        it('should show a specific product', () => {
            //...
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何对使用 CarouselModule 的 Angular 组件进行单元测试 - How to unit test an Angular component which uses CarouselModule 如何对使用Jquery的Angular 6组件进行单元测试 - How to unit test Angular 6 component that uses Jquery 如何在使用 Angular 材质选项卡的组件的单元测试中更改选项卡 - How to change tabs in the unit test of a component that uses Angular Material Tabs 如何编写使用 mergeMap() 的 angular 服务的单元测试? - How to write unit test my angular service which uses mergeMap()? 如何使用Router对Angular 2 RC4组件进行单元测试 - How to unit test Angular 2 RC4 component with Router Angular:如何测试使用“getCurrentNavigation”的组件? - Angular: How can I test component which uses 'getCurrentNavigation'? 如何对具有TemplateRef作为输入的角度组件进行单元测试? - How to make a Unit Test of an Angular Component which has a TemplateRef as Input? 如何对angular7中具有@Input变量的组件进行单元测试? - how to unit test a component which has @Input variables in angular7? 如何测试使用primeng组件的angular组件 - How to test an angular component that uses primeng component 为使用 mat-autocomplete 的组件编写单元测试 - Writing unit test for component which uses mat-autocomplete
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM