1

I want to write a unit test for a method in a service. However the method is written in another service and it is used here. I would like to mock/fake said method.

This is the service:

export class UserService extends ProxyService<UserInterface> {
  constructor() {
    super(new User());
  }
  getOneByEmail(email: string): Observable<any> {
    return this.getUri('user/by-email/').pipe(map((result: any) => result));
  }
  getCurrentUser(): UserInterface {
    return new User().init(localStorage.getItem('user'));
  }
}

This is the part in the proxy service:

getUri(uri: string): Observable<any> {
    return this.remoteStorageService.getUri(uri).pipe(map((result: any) => result));
  }

This is my .spec file for the unit tests:

describe('UserService', () => {
  const data = {
    email: 'test@gmail.com',
  };
  const fakeUser = new User().init(data);
  beforeAll(() => {
    TestBed.initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting()
    );
  });
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        // angular testing module that provides mocking for http connections
        HttpClientTestingModule,
      ],
      // add declaration of services or components and use inject to get to them in tests
      providers: [
        Injector,
        {
          provide: UserService,
          useValue: new User()
        },
      ],
    });
  }));
  beforeEach(() => {
    AppModule.InjectorInstance = TestBed;
    TestBed.inject(UserService);
  });
  it('should be created', () => {
    const service: UserService = TestBed.inject(UserService);
    expect(service).toBeTruthy();
  });
  it('getCurrentUser should return a user', () => {
    const service: UserService = new UserService();
    const user = new User().init();
    expect(service.getCurrentUser()).toEqual(user);
  });
  it('getOneByEmail should return the user who has the specified email', fakeAsync(inject([
    HttpTestingController,
    UserService,
  ], (
    httpMock: HttpTestingController,
    done
  ) => {
    const service = new UserService();
    service.getOneByEmail(data.email).subscribe((res) => {
      expect(res.data.length).toBe(1);
      expect(res.data[0]).toBeInstanceOf(User);
      done();
    });
    const req = httpMock.expectOne('http://projekt.test/by-email/');
    expect(req.request.method).toEqual('GET');
  }
  )));
});

The first 2 tests are working fine. In the subscribe method none of the expects are recognized.

FarkasB
  • 11
  • 1

0 Answers0