如果有人可以查看我缺少的东西,我会很感激,我已经解决了一条路线,该路线会获得在组件中呈现名称的用户。我已经为它创建了一个测试用例,但是得到错误的是无法读取未定义的属性'name'。
组件
<div class="container">
<div class="row">
<div class="col-xs-12">
<span class="headline">{{user.name}}</span>
</div>
</div>
</div>
组件ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Data } from '@angular/router';
import { User } from './../../model/user';
@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.less']
})
export class UserDetailsComponent implements OnInit {
user: User = new User();
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.data
.subscribe(
(data: Data) => {
this.user = data['user'];
}
);
}
}
路线
{ path: 'user-details', component: UserDetailsComponent, resolve: { user: UserResolver} },
测试
describe('Component: User', () => {
let routeStub;
beforeEach(() => {
routeStub = {
data: null
},
TestBed.configureTestingModule({
declarations: [
UserDetailsComponent
],
imports: [
],
providers: [
{ provide: ActivatedRoute, useValue: routeStub }
]
}).compileComponents();
});
it('should render the user name', async(() => {
var user = new User();
user.name = "Alice";
routeStub.data = { user: Observable.of(user) };
let fixture = TestBed.createComponent(UserDetailsComponent);
let component = fixture.debugElement.componentInstance;
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
fixture.whenStable().then(() => {
expect(compiled.querySelector('span').textContent).toContain(user.name);
});
}));
});
错误
Failed: Cannot read property 'name' of undefined
TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer] (ng:///DynamicTestModule/UserDetailsComponent.ngfactory.js:18:34)
at Object.debugUpdateRenderer [as updateRenderer] (webpack:///./node_modules/@angular/core/esm5/core.js?:14909:21)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14023:14)
at callViewAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14369:21)
at execComponentViewsAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14301:13)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14024:5)
at callWithDebugContext (webpack:///./node_modules/@angular/core/esm5/core.js?:15272:42)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (webpack:///./node_modules/@angular/core/esm5/core.js?:14809:12)
at ViewRef_.detectChanges (webpack:///./node_modules/@angular/core/esm5/core.js?:11793:22)
at ComponentFixture._tick (webpack:///./node_modules/@angular/core/esm5/testing.js?:208:32)
更新:我还包括组件ts文件
答案 0 :(得分:1)
ActivatedRoute
类具有data
属性,该属性与解析程序一起分配。我认为你没有正确地嘲笑这个数据对象:
尝试
providers: [
provide: ActivatedRoute,
useClass: class {
data = Observable.of({user : new User({name: "Alice"})})
}
]
OR
routeStub.data = Observable.of({user : new User({name: "Alice"})});