0
votes

Here is the AuthService

export class AuthService {
  constructor(
    private apiService: ApiService,
    private loadingService: LoadingService,
    private router: Router
  ) {}

  private isLoggedIn$$ = new BehaviorSubject(false);
  isLoggedIn$ = this.isLoggedIn$$.asObservable();

  login(userName: string, password: string) {
    const payload = { username: userName, password: password };
    return this.apiService.doPost(Constants.ENDPOINTS.login, payload).pipe(
      tap(() => {
        this.isLoggedIn$$.next(true);
        this.router.navigate(['/' + customerSearchRoutesNames.ROOT]);
      }),
      finalize(() => this.loadingService.isNotLoading())
    );
  }
}

Here is the testing file using Jest

describe('Service: Auth', () => {
  let service: AuthService;
  const apiService = { doPost: jest.fn() };

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [MatSnackBarModule, RouterTestingModule],
      providers: [
        AuthService,
        {
          provide: ApiService,
          useValue: {
            doPost: jest.fn(),
          },
        }
      ],
    });
    service = TestBed.inject(AuthService);
  });

  it('AuthService to be defined', () => {
    expect(service).toBeDefined();
  });

  it('should call login', (done) => {
    const res = { SESSION_ID: 'Test_Session_Id' };
    const url = Constants.ENDPOINTS.login;

    jest.spyOn(apiService, 'doPost').mockResolvedValue(of(res));
    service.login('admin', 'password');
    expect(apiService.doPost).toBeCalledTimes(1);
  });
});

Getting below error. >> ANY HELP ON THIS WOULD BE REALLY APPRECIATED

TypeError: Cannot read properties of undefined (reading 'pipe')

  22 |   login(userName: string, password: string) {
  23 |     const payload = { username: userName, password: password };
> 24 |     return this.apiService.doPost(Constants.ENDPOINTS.login, payload).pipe(
     |                                                                      ^
  25 |       tap(() => {
  26 |         this.isLoggedIn$$.next(true);
  27 |         this.router.navigate(['/' + customerSearchRoutesNames.ROOT]);

I have defined all the mock dependencies but I am still getting the error. I am very new to jest. Any help on this would be really appreciated

1

1 Answers

0
votes

You are mocking the doPost method of the apiService as a function that is returning undefined, but you are trying to call pipe on it. Your mocking function, should return an object, that exposes the pipe method to eliminate this error.