samedi 25 avril 2020

How to mock Angular providedIn: 'root' service

I have a service that I declare as

@Injectable({
    providedIn: 'root'
})
export class AuthService

and used as

constructor(public auth: AuthService)

I've tried to mock it using

let mockAuthService = {
    isAuth: () => true,
    currentUser: { userName: 'Joe' }
};

TestBed.configureTestingModule({
    providers: [
        { provide: AuthService, useValue: mockAuthService }
    ]
});

But karma giving an error

Error: Can't resolve all parameters for MyComponent: (?)

There are two options for solving it:

  • 1. Use providers[] in modules instead of providedIn: 'root'
  • 2. Use @Inject(AuthService) public auth: AuthService in component constructor

Both options are not comme il faut.

How to mock services with providedIn: 'root' properly?

Aucun commentaire:

Enregistrer un commentaire