我刚刚开始在我的应用程序中实现一些测试,尽管我在ActivatedRoute
上遇到了麻烦
我已经按照angular docs
所示设置了activatedRouteStub。import { convertToParamMap, ParamMap, Params } from '@angular/router';
import { ReplaySubject } from 'rxjs';
// An ActivateRoute test double with a `paramMap` observable.
// Use the `setParamMap()` method to add the next `paramMap` value.
export class ActivatedRouteStub {
// Use a ReplaySubject to share previous values with subscribers
// and pump new values into the `paramMap` observable
private subject = new ReplaySubject<ParamMap>();
constructor(initialParams?: Params) {
this.setParamMap(initialParams);
}
/** The mock paramMap observable */
readonly paramMap = this.subject.asObservable();
/** Set the paramMap observables's next value */
setParamMap(params?: Params) {
this.subject.next(convertToParamMap(params));
}
}
然后在我的spec.ts组件中
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AuthFormComponent } from './auth-form.component';
import { ActivatedRoute, Router } from '@angular/router';
import { ActivatedRouteStub } from 'testing/activated-route-stub';
describe('AuthFormComponent', () => {
const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
let component: AuthFormComponent;
let fixture: ComponentFixture<AuthFormComponent>;
let activatedRoute;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AuthFormComponent ],
imports: [
FormsModule,
ReactiveFormsModule,
],
providers: [
{ provide: Router, useValue: routerSpy },
{ provide: ActivatedRoute, useValue: new ActivatedRouteStub() }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthFormComponent);
component = fixture.componentInstance;
activatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
activatedRoute.setParamMap({ _ga: 1886587047.1559712233 });
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
基本上,我的表单中有一个函数可以检查像这样的参数中是否有_ga代码
checkForGACode() {
this.activatedRoute.queryParams
.subscribe((result) => {
if (result._ga) {
this._storage.setSession('_ga', result._ga.split('-')[1]);
}
});
}
但是运行测试时我会得到
不确定在这里做错了什么,我们将不胜感激!
编辑
在另一篇文章中,我看到提供者采用了类似的另一种方式
{ provide: ActivatedRoute, useClass: ActivatedRouteStub }
但是我得到了另一个错误
答案 0 :(得分:0)
您可能可以添加以下代码,它应该可以工作
Provide: ActivatedRoute,
useValue: {
queryParams: returnAMockObservableHere
}
顺便说一句,您可以定义一个类并用UseValue
代替UseClass
。