4

I need to test an Angular 4 service without mock the backend, but got no success.

My beforeEach is as follow:

import { ComponentFixture, TestBed, async } from '@angular/core/testing';

import { RouterStub } from './test-utils/router-stub';
import { MdSnackBarStub } from './test-utils/mdsnackbar-stub';
import { MdDialogStub } from './test-utils/mddialog-stub';

import { HttpModule, Http } from '@angular/http';
import { Router } from "@angular/router";

import { MdSnackBar, MdDialog } from "@angular/material";

import { AuthService } from './auth.service';

describe('AuthService', () => {

  let authService: AuthService;

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      imports: [
        HttpModule,
        FormsModule
      ],
      providers: [
        AuthService,
        { provide: Router, useClass: RouterStub },
        { provide: MdSnackBar, useClass: MdSnackBarStub },
        { provide: MdDialog, useClass: MdDialogStub }
      ]
    }).compileComponents().then((done) => {

      this.authService = TestBed.get(AuthService);
      this.authService.login('myUsername', 'myPassword');

        });

      }));
});

..but for some reason, there is no way to Http really call the API. I know the service is working because it's ok when manually tested. I believe that TestBed is providing a mocked version of Http.

I want this because I need to have the AuthService really logged to do the tests I need. AuthService is holding the token information for user and another data.

May someone give me directions or point me some working example to test a Angular 4 service only?

Thanks.

  • Out of the box Angular CLI does not configure any mocking of modules. Check if you've modified the `test.ts` file or called `TestBed.configureTestingModule` but didn't undo your changes. – Reactgular Aug 21 '17 at 00:50
  • Not really. I left test.ts untouched. Anyway, thanks. I will keep digging. – Jim Bruno Goldberg Aug 22 '17 at 13:29
  • Why not mock the Auth service and provide an implementation of the functions you need to run the tests? You just create a new class MockAuth with the functions and use the same `{ provide: AuthService, useClass: MockAuth }` – Kentonbmax Feb 21 '18 at 14:14

0 Answers0