Ramona
Ramona

Reputation: 255

Unit Testing - Services in ngOnInit: error 'map is not a function'

I try to test a component using Jasmine & Karma, but when I want to test whether the my services have been called in ngOnInit() I get an error that I don't understand:

Failed: Uncaught (in promise): TypeError: tagelers.map is not a function
TypeError: tagelers.map is not a function
    at tagelerService.getTagelers.then (http://localhost:9876/base/src/test.ts?779e448059ef6555f776fac9a62a71930cc82ee7:68007:38)
    ....

My component looks like this:

import ..

@Component({
  selector: 'app-group-details',
  templateUrl: 'group-details.component.html',
  styleUrls: ['group-details.component.css'],
})

export class GroupDetailsComponent implements OnInit {
  @Input()
  tageler: Tageler;
  tagelers: Tageler[];
  group: Group;

  constructor(
    private route: ActivatedRoute,
    private groupService: GroupService,
    private tagelerService: TagelerService) {
  }

  ngOnInit() {
    console.log("Init Details");
    this.route.params
      .switchMap((params: Params) => this.groupService.getGroup(params['id']))
      .subscribe(group => this.group = group);

    this.tagelerService
      .getTagelers()
      .then((tagelers: Tageler[]) => {
        this.tagelers = tagelers.map((tageler) => {
          if (!tageler.title) {
            tageler.title = 'default';
          }
          return tageler;
        });
      });
  }
}

This is how the method looks like in the tagelerService:

getTagelers(): Promise<Tageler[]> {
return this.http.get(this.tagelersUrlGet)
  .toPromise()
  .then(response => response.json() as Tageler[])
  .catch(this.handleError);
}

And this my test is my spec.ts file that fails:

it('should get tagelers when ngOnInit is called', async(() => {
    spyOn(tagelerService, 'getTagelers').and.returnValue(Promise.resolve(Tageler));
    component.ngOnInit();
    fixture.detectChanges();
    expect(tagelerService.getTagelers).toHaveBeenCalled();
}));

Does anyone know why there is a '.map is not a function' error? I guess the problem is a wrong implementation of the 'spyOn' (it does not return what I need), but I don't know how to change it.

Thanks for your help!

Upvotes: 2

Views: 5560

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209092

You're trying to resolve with your Tageler class (which is just a Function, which has no map method).

and.returnValue(Promise.resolve(Tageler));

You need to resolve with an actual array of Tageler instances

Here is where the problem is in your ngOnInit

this.tagelers = tagelers.map((tageler) => {

tagelers is a function (the Tageler class), but it needs be an array

Upvotes: 1

Related Questions