angular - 单元测试角度正确激活路线
问题描述
我刚刚开始在我的应用程序中实施一些测试,ActivatedRoute
但我遇到了麻烦
我已经设置了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 }
但我只是得到一个不同的错误
解决方案
您可能可以添加以下代码行,它应该可以工作
Provide: ActivatedRoute,
useValue: {
queryParams: returnAMockObservableHere
}
顺便说一句,UseValue
您可以定义一个类并将其替换为UseClass
.
推荐阅读
- java - Java Swing Maven - 如何在 jar 文件中加载 ImageIcon
- sql-server - 尝试使用通配符创建此更改表约束
- python - 高效使用numpy select
- ruby-on-rails - Rails - 将二维数组转换为列表并返回
- c# - 如何在 C# .Net Framework 4.6 WPF App 中编写 Python 3 字典
- javascript - 使用 Regex 拆分主题标签和搜索项
- c# - 我想获取鼠标、键盘事件的空闲时间
- spring - 生菜或绝地之间的 Spring Auto Configuration 优先级
- php - Laravel 覆盖组中间件
- spring-boot - 分布式跟踪和弹性堆栈可视化