Nitish
Nitish

Reputation: 661

Mock Observable service on ngOnInit

PS This is first time I will be writing test cases.

Env details: - Angular 4.4.3

in component

currentToken: string;

constructor(private tokenService: TokenService){}

ngOnInit(): void {
   this.tokenService.getCurrentToken().subscribe((token: string) => {
      this.currentToken = token;
   });
}

in TokenService

export class TokenService {
   constructor(private router: Router) { }

   getCurrentToken(): Observable<string> {
      const token: string = sessionStorage.getItem("token");
      if (token) {
         return Observable.of(token);
      }else {
         this.router.navigate(['home']);
      }
   }
}

In spec.ts

describe("AccountComponent" , () => {
   let component: AccountComponent;
   let fixture: ComponentFixture<AccountComponent>;

   beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [],
        declaration: [ TokenService ]
      }).compileComponents();
   }));

   beforeEach(() => {
     fixture = TestBed.createComponent(AccountComponent);
     component = fixture.createInstance;
     fixture.detectChanges();
     component.ngOnInit();
   });

   it("should create", () => {
     expect(component).toBeTruthy();
   });
});

This is simple test which will come when i used angular cli. As you may be already know that I am getting error like below.

"Cannot read property 'subscribe' of undefined"

This is common kind of method which i will writing in all new component.

TIA

Upvotes: 1

Views: 2290

Answers (1)

Aravind
Aravind

Reputation: 41571

You should be using a FakeService as below,

  • Define a fake class with the method returning some string.
  • The class
  • Inject the provider in the beforeEach()
  • In the it block modify it to the toBeDefined() as the component cannot be truthy

    describe("AccountComponent" , () => {
       let component: AccountComponent;
       let fixture: ComponentFixture<AccountComponent>;
       let tokenService : TokenService;
       class FakeTokenService {
            getCurrentToken(){
                Observable.of('some string')
            }
       }
    
       beforeEach(async(() => {
          TestBed.configureTestingModule({
            imports: [],
            declaration: [ ],
            providers: [
                { provide: TokenService, useClass: FakeTokenService }
            ]
          }).compileComponents();
       }));
    
       beforeEach(() => {
         fixture = TestBed.createComponent(AccountComponent);
         component = fixture.createInstance;
         fixture.detectChanges();
         fixture.debugElement.injector.get(TokenService);
       });
    
       it("should create", () => {
         expect(component).toBeTruthy();
       });
    });
    

Upvotes: 2

Related Questions