测试使用ActivatedRoute的组件有一个大问题 - 我只想传递默认测试“component.toBeTruthy”
组件类:
@Component({
selector: 'app-room',
templateUrl: './room.component.html',
styleUrls: ['./room.component.css']
})
export class RoomComponent implements OnInit {
roomId:string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.roomId = this.route.snapshot.params.id;
}
}
测试:
describe('RoomComponent', () => {
let component: RoomComponent;
let fixture: ComponentFixture<RoomComponent>;
beforeEach(async(() => {
let temp = new ActivatedRouteStub();
TestBed.configureTestingModule({
declarations: [ RoomComponent ],
imports: [MaterialModule, FormsModule, RouterModule, BrowserModule,BrowserAnimationsModule],
providers: [MatDialog, MatToolbar, RoomService,
{
provide: ActivatedRoute, useValue: {}
}
],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RoomComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
问题是,当我开始测试时,它会因奇怪的错误而失败:
Chrome 65.0.3325(Mac OS X 10.13.4)错误 { “message”:“Uncaught NetworkError:无法在'XMLHttpRequest'上执行'send':无法加载'ng:///DynamicTestModule/RoomComponent_Host.ngfactory.js'。\ nat http://localhost:9876/_karma_webpack_/polyfills.bundle.js:2206:25 \ n \ n错误:失败在'XMLHttpRequest'上执行'send':无法在XMLHttpRequest.proto的http://localhost:9876/_karma_webpack_/polyfills.bundle.js:4970:35 \ n加载'ng:///DynamicTestModule/RoomComponent_Host.ngfactory.js'。\ n。(匿名函数)[as send ](http://localhost:9876/_karma_webpack_/polyfills.bundle.js:3386:24)\ n在Array。(node_modules / source-map-support / browser-source-map-support.js:107:134)\ n在node_modules / source-map-support / browser-source -map-support.js:101:106 \ n
如果我从ngOnInit中删除此行this.roomId = this.route.snapshot.params.id;
,一切正常。
发生了什么事?
答案 0 :(得分:0)
我的直觉说错误消息可能与实际问题无关。
问题在于您正在使用{}
作为ActivatedRoute
的提供者。然后,在组件中,您尝试访问ActivatedRoute
,在测试用例中为{}
。
您可以尝试将providers
替换为:
providers: [MatDialog, MatToolbar, RoomService,
{
provide: ActivatedRoute, useValue: {
snapshot: { params: { id: 123 } }
}
}];