我的component.ts文件看起来像
import { Component, OnInit } from '@angular/core';
import { select } from 'ng2-redux';
import { Observable } from 'rxjs/Observable';
import { PersonalDetailsComponent } from '../personal-details/personal-details.component'
@Component({
selector: 'app-profile-details',
templateUrl: './profile-details.component.html'
})
export class ProfileDetailsComponent implements OnInit {
@select(['customerData', 'personalDetails'])personalDetails:Observable<object>; //<------if i comment out @select statement, then the tests work
@select(['loading']) loading: Observable<boolean>;//<------if i comment out @select statement, then the tests work
constructor() { }
ngOnInit() { }
}
和我的茉莉测试看起来像
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NgRedux, select } from 'ng2-redux';
import { ProfileDetailsComponent } from './profile-details.component';
import { customerData } from '../data/customerProfileDataMock';
import { PersonalDetailsComponent } from '../personal-details/personal-details.component'
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
class RouterStub { navigate(params) { } }
class MockSelect { }
class MockObservable<T> {}
class NgReduxStub {
constructor() { }
dispatch = () => undefined;
getState = () => { return customerData; };
subscribe = () => undefined;
}
describe('ProfileDetailsComponent', () => {
let component: ProfileDetailsComponent;
let fixture: ComponentFixture<ProfileDetailsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ProfileDetailsComponent, PersonalDetailsComponent],
providers: [
{ provide: Router, useClass: RouterStub },
{ provide: select, useClass: MockSelect },
{ provide: NgRedux, useClass: NgReduxStub },
{ provide: Observable, useClass: MockObservable }
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProfileDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the profile details page', () => {
expect(component).toBeTruthy();
});
});
不确定缺少什么,但是当我使用命令'ng test'运行测试'
时,@Select语句不会被模拟并遇到以下错误TypeError: ng_redux_1.NgRedux.instance is undefined in src/test.ts
不确定您是否正在使用与我相同的软件包,但我注意到NG2-REDUX在NPM上(https://www.npmjs.com/package/package/ng2-redux(链接到github存储库https://github.com/angular-redux/store,所以也许有一些分支合并。
如果是这样,我建议您包装更新。他们最近添加了Mockngredux,您可以将其添加到测试中
import { NgReduxTestingModule, MockNgRedux } from '@angular-redux/store/testing';
用
添加到测试中beforeEach(() => {
TestBed.configureTestingModule({
imports: [
NgReduxTestingModule,
],
,可用于测试使用
上的特定选择器上的值来测试使用@select()
的组件 const stub = MockNgRedux.getSelectorStub(selector);
stub.next(values);
stub.complete();
请注意,方法是静态的,不需要Mockngredux实例。
确保清除测试之间的模拟存储
beforeEach(() => {
MockNgRedux.reset();
});