vendredi 10 mai 2019

service test, spyOn.returnValue doesn't return given value

ApiServiceSpy

export class ApiServiceSpy {
  get() {
    return Observable.of(null);
  }
}

UserService

export class UserService {
  constructor(private apiService: ApiService) {
    this.initUser();
  }

  initUser() {
    this.fetchUser().subscribe(user => console.log(user.name));
  }

  fetchUser(): {name: string} {
    return this.apiService.get('user');
  }
}

UserService.spec

export class UserServiceSpec {
  ...
  {
    providers: [
      {provide: ApiService, useClass: ApiServiceSpy}
    ]
  }
  ...

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
}

Okay, so now the 'should be created' test fails because the service's constructor calls initUser method which uses fetchUser and tries to get into user.name but the apiService.get returns null so we can't read name of null - understandable.

So I'm trying to spy on the fetchUser method

UserService.spec

export class UserServiceSpec {
  ...
  {
    providers: [
      {provide: ApiService, useClass: ApiServiceSpy}
    ]
  }
  ...

  beforeEach(() => {
    spyOn(service, 'fetchUser').and.returnValue(Observable.of({name: 'Daniel'});
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
}

Unfortunately the result is the same. How is this possible? I just spied on the whole fetchUser method but the spec is still treating the apiService.get spy as more important.

Aucun commentaire:

Enregistrer un commentaire