angular - 带有 ActivatedRoute 的 Angular 测试组件
问题描述
我对使用 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) ERROR { "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”上执行“发送”:无法加载“ng:///DynamicTestModule/RoomComponent_Host” .ngfactory.js'.\n 在http://localhost:9876/_karma_webpack_/polyfills.bundle.js:4970:35 \n 在 XMLHttpRequest.proto.(匿名函数)[作为发送](http://localhost: 9876/_karma_webpack_/polyfills.bundle.js:3386:24)\n 在数组中。(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
如果我this.roomId = this.route.snapshot.params.id;
从 ngOnInit 中删除这一行,一切正常。
发生了什么?
解决方案
我的直觉说错误消息可能与实际问题无关。
问题是您正在{}
用作ActivatedRoute
. 然后,在您的组件中,您尝试访问ActivatedRoute
在测试用例中是{}
.
您可以尝试将您的替换providers
为:
providers: [MatDialog, MatToolbar, RoomService,
{
provide: ActivatedRoute, useValue: {
snapshot: { params: { id: 123 } }
}
}];
推荐阅读
- javascript - 使用 php 检测任何设备,如计算机、手机、平板电脑
- visual-studio-code - 保存所有文件时自动执行系统命令
- php - 通过 ajax 读取 txt 文件
- java - Spring Reactive Router Path - 带排除的通配符
- asynchronous - Flutter:如何将 TextField 文本传递给 API 请求?
- cassandra - 提高 cassandra 的性能
- python - 如何从 JSON 数据中解析数据?
- c# - Starting an async Task running for the lifetime of an object
- javascript - 如何使用 html 选择选项在表上显示 sql 查询结果?
- elasticsearch - elasticsearch 7.3“字段扩展匹配太多字段”