Javascript 未定义的单元测试不是对象(正在评估“this.groups.map”)
我有剧本Javascript 未定义的单元测试不是对象(正在评估“this.groups.map”),javascript,angular,unit-testing,typescript,karma-jasmine,Javascript,Angular,Unit Testing,Typescript,Karma Jasmine,我有剧本 groups: Group[] = [] constructor( ) { this.groups = AuthenticationService.getUserGroups() let menuList: any = [] this.groups.map((permission: Group) => { menuList.push(...this.menuGenerator[permission.nomeGrupo.split
groups: Group[] = []
constructor(
) {
this.groups = AuthenticationService.getUserGroups()
let menuList: any = []
this.groups.map((permission: Group) => {
menuList.push(...this.menuGenerator[permission.nomeGrupo.split('-')[1]])
})
}
当我运行npm运行测试时,只是显示错误类型error:undefined不是一个计算“this.groups.map”的对象。我想知道解决这个问题的最好方法是什么。我把spyOn放在getUserGroups上,但不起作用。如何为变量设置一些值?谢谢!我真的需要学习 放置间谍将取代您的功能 这意味着它不再返回任何内容 这意味着你从
groups = [];
然后你监视你的函数
spyOn(AuthenticationService, 'getUserGroups');
然后你得到
groups = undefined;
要解决此问题,只需在spy中返回一个值:
spyOn(AuthenticationService, 'getUserGroups').and.returnValue([]);
编辑因为您在构造函数中,所以不能监视组件本身,因为它不是创建的
很高兴你有了原型遗传。您可以监视原型,而不是监视服务实例:
spyOn(AuthenticationService.prototype, 'getUserGroups').and.returnValue([]);
你应该把它放在你描述的“MyComponent”下面,所以这是第一个被称为MyComponent的东西 太好了!但我把它放在哪里了?我把它放在夹具前。检测改变!但是不起作用…等等,我没看到你在构造器里。让我编辑我的问题。太好了!我现在就试试,但如果spyOn可以在Constructor中进行间谍,那么最好的脚本放置方式是什么?ngOnInit?我在“getUserGroups”中输入.prototype时出错了=那太好了是的!你犯了什么样的错误?