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()
中,无论我放置{{1}}的位置如何,该错误仍然存在。
我知道我可以简单地使用可观察对象而不是存根,但是出于好奇,您知道我在做什么错吗?我应该怎么做才能使它正常工作?
答案 0 :(得分:0)
您需要使其async
beforeEach(async(() => {
activatedRoute.setParamMap({ id: 1 });
}