角度测试存根和打字稿

时间:2017-05-21 16:32:51

标签: angular typescript

我一直关注角testing guide并设置我的一项测试,如下所示

let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let activatedRoute: ActivatedRouteStub;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [
            {provide: ActivatedRoute, useClass: ActivatedRouteStub},
            {provide: Router, useClass: RouterStub}
        ]
    });
}));

beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    activatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
    activatedRoute.testParams = { email: email};
    fixture.detectChanges(); // calls ngOnInit
});

,其中

@Injectable()
export class ActivatedRouteStub {
    // ActivatedRoute.params is Observable
    private subject = new BehaviorSubject(this.testParams);
    params = this.subject.asObservable();

    // Test parameters
    private _testParams: {};
    get testParams() { return this._testParams; }
    set testParams(params: {}) {
        this._testParams = params;
        this.subject.next(params);
    }

    // ActivatedRoute.snapshot.params
    get snapshot() {
        return { params: this.testParams };
    }
}

在我执行npm install更新包(Angular 4和typescript)之前,这一切都很顺利,现在我收到以下错误

TS2322: Type 'ActivatedRoute' is not assignable to type 'ActivatedRouteStub'.
  Property 'subject' is missing in type 'ActivatedRoute'.

TS2339: Property 'parent' does not exist on type 'ActivatedRouteStub'.

为什么我会突然遇到这些错误?

1 个答案:

答案 0 :(得分:0)

问题在于它正在尝试检索ActivatedRoute类,并分配到ActivatedRouteStub。修复是以下内容:

let activatedRoute: ActivatedRouteStub;
 ...
activatedRoute = fixture.debugElement.injector.get(ActivatedRoute) as any;