1

Angular 文档提到了 ActivatedRoute 的测试替身:

import { convertToParamMap, ParamMap, Params } from '@angular/router';
import { ReplaySubject } from 'rxjs';

  export class ActivatedRouteStub {
    private subject = new ReplaySubject<ParamMap>();

    constructor(initialParams?: Params) {
      this.setParamMap(initialParams);
    }

    readonly paramMap = this.subject.asObservable();

    setParamMap(params?: Params) {
      this.subject.next(convertToParamMap(params));
    };
  }

但是当我在我的组件中使用它时 -

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TypesComponent } from './types.component';
import { ActivatedRoute } from '@angular/router';
import { ActivatedRouteStub } from './../../testing/activated-route-stub';

describe('Component', () => {
let component: TypesComponent;
let fixture: ComponentFixture<TypesComponent>;
let activatedRoute: ActivatedRouteStub;

beforeEach(async(() => {

    TestBed.configureTestingModule({
        declarations: [ TypesComponent ],
        providers: [
            { provide: ActivatedRoute, useValue: ActivatedRouteStub}            
        ]
    })
    .compileComponents();
}));

beforeEach(() => {
    activatedRoute = TestBed.get(ActivatedRoute);
});

beforeEach(() => {
    fixture = TestBed.createComponent(TypesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', () => {
    expect(component).toBeTruthy();
});

it('should get...', () => {
    activatedRoute.setParamMap({ id: 1});
    spyOn(service, 'method').and.returnValue(1);
    expect(service.value).toHaveBeenCalledWith(1);
   });
});

但这给出了错误: 在此处输入图像描述

编辑:无论我将.setParamMap()-放在哪里,这个错误都会持续存在。it()beforeEach()

我知道我可以简单地使用 observable 而不是存根,但出于好奇,知道我在这里做错了什么吗?我应该怎么做才能让它工作?

4

1 回答 1

0

你需要做到async

  beforeEach(async(() => {
    activatedRoute.setParamMap({ id: 1 });
  }
于 2018-06-25T10:42:22.697 回答