首页 > 解决方案 > 单元测试角度正确激活路线

问题描述

我刚刚开始在我的应用程序中实施一些测试,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 }

但我只是得到一个不同的错误

在此处输入图像描述

标签: angularkarma-jasmine

解决方案


您可能可以添加以下代码行,它应该可以工作

 Provide: ActivatedRoute,
 useValue: {
    queryParams: returnAMockObservableHere
 }

顺便说一句,UseValue您可以定义一个类并将其替换为UseClass.


推荐阅读