spyOn method returns error "method does not exist"

Viewed 1848

I am writing a test case to test an effect that refreshes token every time the action is called . I have created a mock service to mock the response of the endpoint my effect actually calls . Here is the test.

import { JwtHelperService } from '@auth0/angular-jwt';
import { Observable, of } from "rxjs";
import { AuthEffects } from './auth.effects';
import { provideMockActions } from '@ngrx/effects/testing';
import { AuthService } from '../services/AuthService.service';
import { TestBed } from '@angular/core/testing';
import { AuthActions } from './action-types';

const newToken = "Bearer : 123456789";

class MockService {
  refreshToken ( ) {
    return of(newToken);
  }
}


describe('AuthEffects', () => {
  let actions$: Observable<any>;
  let effects: AuthEffects;
  let httpService: AuthService;
  let jwtHelper: JwtHelperService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        AuthEffects,
        provideMockActions(() => actions$),
        [{ provide: AuthService, useValue: MockService }],
        [{ provide: JwtHelperService, useValue: MockService }],

      ],
    });
    effects = TestBed.get(AuthEffects);
   
    httpService = TestBed.get(AuthService);
    jwtHelper = TestBed.get(JwtHelperService);
  });
  describe('refreshToken$', () => {
    it('should hit refresh token api ', (done) => {
      const spy = spyOn(httpService, 'refreshToken').and.callThrough();
      actions$ = of(AuthActions.refreshToken);
      effects.refreshToken$.subscribe((res) => {
        expect(res).toEqual(AuthActions.tokenRefreshSuccessful({  newToken }));
        expect(spy).toHaveBeenCalledTimes(1);
        done();
      });
    });
  });
});

The effect I was testing is this

refreshToken$ = createEffect(
    () => this.actions$.pipe(
        ofType(AuthActions.refreshToken),
        concatMap((action) => this.authService.refreshToken(action.oldToken)),
        map(newToken => {
            return AuthActions.tokenRefreshSuccessful({ newToken })
        }),
        catchError((error) => {
            return of(AuthActions.tokenRefreshFail(error))
        })
    )
);

The issue that I face when I run the test case is this

Error: <spyOn> : refreshToken() method does not exist
Usage: spyOn(<object>, <methodName>)
1 Answers

Got the issue. I was using useValue instead of useClass for injecting the service

Related