简体   繁体   中英

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') . I want to know what is the best way do fix that. I put spyOn to getUserGroups , but isn't work. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM