使用Jasmin和Karma在Angular 2中使用单元测试。
我需要模仿以下代码
this.activatedRoute.url.subscribe(url => {
debugger;
this.isEdit = false;
if (url[0].path === 'updatecoc') {
this.isEdit = true;
}
});
我试过这种方式嘲笑: How to mock an activatedRoute parent Route in angular2 for testing purposes?
let fakeActivatedRoute = new MockActivatedRoute();
fakeActivatedRoute.parent = new MockActivatedRoute();
let urlSegment: UrlSegment[] = [];
urlSegment.push({ path: "updatecoc", parameters: {} });
fakeActivatedRoute.url = Observable.of(urlSegment);
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, MessagesModule, DataTableModule, DropdownModule, ConfirmDialogModule, AccordionModule,
AutoCompleteModule, DialogModule, EditorModule, HttpModule],
declarations: [MaintainCOCComponent],
providers: [{ provide: MaintainCOCService, useClass: MaintainCOCService },
{ provide: Configuration, useClass: Configuration },
{ provide: Router, useClass: MockRouter },
{ provide: ActivatedRoute, useClass: fakeActivatedRoute }];
但是在模拟ActivatedRoute
模块时遇到错误。我已经尝试过2天了。我无法解决这个问题。
完整的错误消息是:
Object doesn't support this action
at _ActivatedRoute_58.get (Function code:173:46)
at DynamicTestModuleInjector.prototype.getInternal (Function code:281:43)
at NgModuleInjector.prototype.get (http://localhost:9876/base/src/test.ts:60528:9)
at TestBed.prototype.get (http://localhost:9876/base/src/test.ts:17440:13)
at AppView.prototype.injectorGet (http://localhost:9876/base/src/test.ts:89000:17)
at DebugAppView.prototype.injectorGet (http://localhost:9876/base/src/test.ts:89428:13)
at View_MaintainCOCComponent_Host0.prototype.createInternal (Function code:20:3)
at AppView.prototype.createHostView (http://localhost:9876/base/src/test.ts:88956:9)
at DebugAppView.prototype.createHostView (http://localhost:9876/base/src/test.ts:89412:13)
at ComponentFactory.prototype.create (http://localhost:9876/base/src/test.ts:44498:9)
注意:我应该为解决的答案提供赏金。
答案 0 :(得分:2)
发生错误是因为您使用useClass
提供程序选项注册现有对象。
当注入器解析ActivatedRoute
依赖项时,它会看到注册的提供程序具有useClass
属性,并尝试将该属性的值实例化为构造函数。
由于您有现有值fakeActivatedRoute
,您可以使用useValue
属性注册
providers: [{provide: ActivatedRoute, useValue: fakeActivatedRoute}]
或者,您可以注册MockActivatedRoute构造函数,而不是创建实例
providers: [{provide: ActivatedRoute, useClass: MockActivatedRoute}]
此外,您的注册码可以而且应该从
简化providers: [
{ provide: MaintainCOCService, useClass: MaintainCOCService },
{ provide: Configuration, useClass: Configuration },
{ provide: Router, useClass: MockRouter },
{ provide: ActivatedRoute, useClass: fakeActivatedRoute }
]
到
providers: [
MaintainCOCService,
Configuration,
{ provide: Router, useClass: MockRouter },
{ provide: ActivatedRoute, useValue: fakeActivatedRoute }
]