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 而不是存根,但出于好奇,知道我在这里做错了什么吗?我应该怎么做才能让它工作?