Angular + Jasmine:无法监视ActivatedRoute.queryParams

时间:2018-03-04 14:31:41

标签: angular testing jasmine

如何监视预期会返回Observable的存根角色服务方法,例如ActivatedRoute.queryParams。这是我失败的规范:

import { TestBed, ComponentFixture } from "@angular/core/testing";
import { RivalChartComponent } from "./rival-chart-component";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { ActivatedRoute, RouterModule, Router } from "@angular/router";
import { appRoutes } from "../app.routes";
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/of';

describe('RivalChartComponent', () => {

    let component: RivalChartComponent;
    let fixture: ComponentFixture<RivalChartComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [
                RivalChartComponent
            ],
            imports: [FormsModule, ReactiveFormsModule],
            providers: [
                {provide: ActivatedRoute, useValue: {queryParams: Observable.of({tags:'all'})}},
                {provide: Router, useValue: {}}
            ]
        });
        fixture = TestBed.createComponent(RivalChartComponent);
        component = fixture.componentInstance;
    });

    it('should init selectedTags as empty string when no query parameter is set', () => {
        spyOn(fixture.debugElement.injector.get(ActivatedRoute), 'queryParams').and.returnValue(Observable.of({tags:null}));
        component.ngOnInit();
        expect(component.selectedTags.value).toEqual('')
    });

});

以下是相应的源代码:

import { Component, OnInit } from '@angular/core';
import { Rival } from '../domain/rival';
import { Route, ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormControl } from '@angular/forms';
import { CompairValidators } from '../validators/CompairValidators';

@Component({
    moduleId: module.id,
    selector: 'cp-rival-chart',
    templateUrl: 'rival-chart.html'

})
export class RivalChartComponent implements OnInit {

    rivals: Array<Rival> = [];
    selectedTags: FormControl;

    constructor(private route: ActivatedRoute, private router: Router) {
        this.selectedTags = new FormControl('', CompairValidators.trimmedArrayMinLengthValidator(3,1));
    }

    ngOnInit() {
        this.updateInputFromQueryParams();
    }

    updateInputFromQueryParams() {
        this.route.queryParams.subscribe((params) => {
            this.selectedTags.patchValue(this.createInputTagsFromUrlTags(params.tags));
        });
    }

    createInputTagsFromUrlTags(tags: String): string {
        if (!tags) {
            return '';
        }
        const tagsArray = tags.split('+');
        const cleanedTags = tagsArray
            .filter((tag) => tag && tag.trim());
        return '#' + cleanedTags.join(' #');
    }

}

代码应该从ActivatedRoute服务给出的查询参数named tags初始化selectedTags FormControl。如果没有给出查询参数,则应使用空String初始化selectedTags。为了测试它,我想监视ActivatedRoutes.queryParams方法并为键标签返回一个空字符串,但不幸的是它不起作用。相反,最初传递的ActivatedRoute存根的Observable被调用,它返回String&#39; all&#39;对于关键标签。因此,我的测试失败,并显示以下消息:

  

预期&#39;#all&#39;等于&#39;。

您可能会想为什么ActivatedRoute存根不会直接返回空字符串或空字符串。那是因为我的规范中实际上有其他测试,我没有在这里添加,以便专注于我的主要问题。

1 个答案:

答案 0 :(得分:-1)

您的测试应在async测试区内执行,以处理ObservablePromise。有几种方法可以做到这一点

以下是async关键字的示例:

it('should init selectedTags as empty string when no query parameter is set', async(() => {
        spyOn(fixture.debugElement.injector.get(ActivatedRoute), 'queryParams').and.returnValue(Observable.of({tags:null}));
        component.ngOnInit();
        expect(component.selectedTags.value).toEqual('')
    }));