angular - Jasmine 模拟调用服务而不是模拟值
问题描述
我有这个方法,它在里面调用一个服务。
searchUser() {
this.isLoading = true;
this.usersService.searchEmailandName(this.corporateId.value).subscribe(
(data: UserSearch) => {
this.isLoading = false;
this.email.patchValue(data.email);
this.name.patchValue(data.name);
this.checkInputs();
}, error => {
this.isLoading = false;
this.errorGeneric.errorGeneric(error, 'search_user');
this.email.patchValue('');
this.name.patchValue('');
}
);
}
我正在尝试正确测试它:
it('should test searchUser ', (done) => {
usersService = TestBed.get(UsersService);
component.corporateId.patchValue(userProfile.user.corporateId);
component.searchUser();
spyOn(usersService, 'searchEmailandName').and.returnValue(of(userProfile.user));
expect(component.email.value).toBe('mock name');
expect(component.name.value).toBe('mock@email.com');
done();
});
用户个人资料包含我需要嘲笑的所有信息。我收到此错误
Error: Expected undefined to be 'mock name'.
所以我可能没有正确地做间谍,或者只是误解了它是如何工作的
解决方案
spyOn
在调用该方法之前尝试执行。
it('should test searchUser ', (done) => {
usersService = TestBed.get(UsersService);
component.corporateId.patchValue(userProfile.user.corporateId);
// spy first before calling the method
spyOn(usersService, 'searchEmailandName').and.returnValue(of(userProfile.user));
component.searchUser();
expect(component.email.value).toBe('mock name');
expect(component.name.value).toBe('mock@email.com');
done();
});
推荐阅读
- list - TCL:使用 lsearch 在列表中搜索包含特定字符的元素
- database - 将 InfluxDB 系列映射到包含所有元数据的 MongoDB 集合
- angular - 在 Angular 4 中解密字符串消息
- ios - userContentController 永远不会被调用
- javascript - 页面重新加载将用户重定向到主页以做出反应
- xml - 错误:使用 Chrome 打开在 namespaceURI 中包含特殊字符的 Xml 文件
- java - 如何比较来自数据库和用户输入的字符串?
- unity3d - 未使用 Destroy() 删除的 Unity 协程和对象
- javascript - jquery ui sortable:如何放入嵌套容器
- python - 错误消息“无法转换
* 到 Python 对象”在 Cython