我在当前应用程序中使用 angular 2.1.0 模块。如果我在具有 routerLink 属性的组件上运行单元测试,我会收到以下错误。
Failed: Uncaught (in promise): Error: Error in ./MyComponent class MyComponent - inline template:7:24 caused by: Cannot read property 'subscribe' of undefined
Error: Uncaught (in promise): Error: Error in ./MyComponent class MyComponent - inline template:7:24 caused by: Cannot read property 'subscribe' of undefined
at resolvePromise (webpack:///home/admin1/amplifyr-web/~/zone.js/dist/zone.js:429:0 <- src/test.ts:82249:31)
at webpack:///home/admin1/amplifyr-web/~/zone.js/dist/zone.js:465:0 <- src/test.ts:82285:17
at ZoneDelegate.invokeTask (webpack:///home/admin1/amplifyr-web/~/zone.js/dist/zone.js:236:0 <- src/test.ts:82056:37)
at ProxyZoneSpec.onInvokeTask (webpack:///home/admin1/amplifyr-web/~/zone.js/dist/proxy.js:96:0 <- src/test.ts:56854:39)
at ZoneDelegate.invokeTask (webpack:///home/admin1/amplifyr-web/~/zone.js/dist/zone.js:235:0 <- src/test.ts:82055:42)
at Zone.runTask (webpack:///home/admin1/amplifyr-web/~/zone.js/dist/zone.js:136:0 <- src/test.ts:81956:47)
at drainMicroTaskQueue (webpack:///home/admin1/amplifyr-web/~/zone.js/dist/zone.js:368:0 <- src/test.ts:82188:35)
Expected undefined to be truthy.
at webpack:///home/admin1/amplifyr-web/src/app/workflow/my.component.spec.ts:131:21 <- src/test.ts:33693:22
at TestBed.execute (webpack:///home/admin1/amplifyr-web/~/@angular/core/bundles/core-testing.umd.js:864:0 <- src/test.ts:3973:23)
at Object.<anonymous> (webpack:///home/admin1/amplifyr-web/~/@angular/core/bundles/core-testing.umd.js:951:32 <- src/test.ts:4060:49)
我在我的组件中使用路由参数和数据解析。我按照文档中的说明设置了 ActivatedRouteStub 和 RouterStub。这是我的 TestBed 配置。帮助我克服错误。
beforeEach(异步(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent,
DummyComponent,
RouterLinkStubDirective
],
imports: [
RouterTestingModule.withRoutes(
[
{
path: '',
redirectTo: '/projects',
pathMatch: 'full'
},
{
path: 'projects',
component: DummyComponent
}
]
)
],
providers: [
{ provide: ComponentFixtureAutoDetect, useValue: true },
{provide: ActivatedRoute, useValue: ActivatedRouteStub},
{provide: Router, useValue: RouterStub}
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents().then(() => {
mockActivatedRoute = new ActivatedRouteStub();
mockActivatedRoute.testParams = {'_id': 19}, {'ff': {'dt': { 'ns': [], 'cs': []}}, 'rs': { 'dt': []}};
fixture = TestBed.createComponent(MyComponent);
// get test component from the fixture
comp = fixture.componentInstance;
});
}));