我有一个UserManagementService
,它暴露了Observable
中的BehaviourSubject
。
this.userSignInState$ = this.signInStateSubject.asObservable();
我在userSignInState
组件中订阅了nav
。
constructor(public userManagementService: UserManagementService, private fb:FormBuilder, private helper:HelperService) {
this.userSignInStateSubscription = this.userManagementService.userSignInState$.subscribe(
(result:Result)=> {
console.log("In nav - result from user signin state ",result);
let subscribed:UserSigninState = result.additionalInfo;
console.log("new user signin state received:", subscribed);
this.userLoggedIn = subscribed.isSignedIn;
if(subscribed.isSignedIn && subscribed['additional-info'] !== ''){
this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI
}
if(!subscribed.isSignedIn && subscribed['additional-info'] !== ''){
// let error:ServerResponseAPI = JSON.parse(subscribed['additional-info']) as ServerResponseAPI
//let errorMessage:string = this.helper.userFriendlyErrorMessage(error);
this.navEvent.emit(new NavContext(subscribed['additional-info']));
}
},
(error:ServerResponseAPI)=>{
console.log("got error from the Observable: ",error);
let errorMessage:string = this.helper.userFriendlyErrorMessage(error);
this.navEvent.emit(new NavContext(errorMessage));
// this.userloggedIn =false;
},
()=>{ //observable complete
console.log("observable completed")
//this.userloggedIn =false;
});
}
我想对nav
进行单元测试。 spec
应该测试component
订阅了userSignInState$
并正确处理Result
。我该怎么做呢?由于这是单元测试,因此我不想使用真正的UserManagementService
我编写了以下规范
fit('should subscribe to user sign in state observable',()=>{
let userManagementService = TestBed.get(UserManagementService);
let navComponent:NavComponentComponent = component;
console.log('component is ',navComponent);
navComponent.userLoggedIn = false;
let dummyUserProfile = new UserProfileAPI(new User('fn','ln','test@test.com'));
userManagementService.signInStateSubject.next(new Result('success',(new UserSigninState(true,JSON.stringify(dummyUserProfile ))).toString));
expect(navComponent.userLoggedIn).toBe(true)
});
但是我收到错误消息Expected undefined to be true.
我不明白为什么userLoggedIn
未定义。我在nav
类中声明了它
export class NavComponentComponent implements OnInit {
userLoggedIn:boolean;
...
}
我在ngOnInit
中设置了它。
ngOnInit(){
this.userLoggedIn = false;
...
}
我也将订阅逻辑移至ngOnInit
,但这也不起作用,并且给出了相同的结果。
答案 0 :(得分:0)
问题出在我创建Result
的方式上。我不应该将.toString
与userSignInState
一起使用。关于我在SO
中发布的另一个问题,“对不带()的.toString的引用只是对该函数的引用,因此,如果您记录下来,则可以获取该函数的代码。”另外,“ toString()将不起作用,因为userSignInState没有有意义的字符串表示,并且默认为[object Object]”。我删除了toString
,工作为additional-info
的代码属于any