[英]unit test undefined is not an object (evaluating 'this.groups.map')
I have that script 我有那个剧本
groups: Group[] = []
constructor(
) {
this.groups = AuthenticationService.getUserGroups()
let menuList: any = []
this.groups.map((permission: Group) => {
menuList.push(...this.menuGenerator[permission.nomeGrupo.split('-')[1]])
})
}
And when I run npm run test
, just appear that error TypeError: undefined is not an object (evaluating 'this.groups.map')
. 当我运行
npm run test
,只是出现错误TypeError: undefined is not an object (evaluating 'this.groups.map')
。 I want to know what is the best way do fix that. 我想知道什么是最好的解决方法。 I put
spyOn
to getUserGroups
, but isn't work. 我把
spyOn
到getUserGroups
,但不起作用。 How can I put some value for the variable? 如何为变量添加一些值? Thanks a lot!
非常感谢! I really need to learn that!
我真的需要学习!
Putting a spy replaces your function. 放置间谍将取代您的功能。
This means that it doesn't return anything anymore. 这意味着它不再返回任何内容。
This means that you start with 这意味着您从
groups = [];
Then you spy on your function 然后你监视你的功能
spyOn(AuthenticationService, 'getUserGroups');
And then you get 然后你得到
groups = undefined;
To resolve that, simply return a value in your spy : 要解决这个问题,只需在间谍中返回一个值:
spyOn(AuthenticationService, 'getUserGroups').and.returnValue([]);
EDIT Because you're in the constructor, you can't spy on the component itself, since it isn't created. 编辑因为您在构造函数中,所以您无法监视该组件本身,因为它没有被创建。
Gladly for you, you have the prototypal inheritance. 高兴地为您提供原型继承。 Instead of spying on the service instance, you can spy on the prototype :
除了监视服务实例,您还可以监视原型:
spyOn(AuthenticationService.prototype, 'getUserGroups').and.returnValue([]);
You should put this right under your describe('MyComponent')
, so that's the first thing called. 您应该将此权限放在
describe('MyComponent')
,因此这是第一件事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.