angularkarma-jasmineangular2-routingangular2-testingangular2-router3

How do I Mock an Angular 2 route?


I have the following code...

export class LoginComponent {
    userName: string;
    password: string;
    rememberMe: boolean = false;
    constructor( private auth: AuthenticationService,
                 private router: Router) {
      ...
    }
    ...
}

I am trying to Unit test but my first attempt failed....

beforeEach(() => {
        router = new Router();
        component = new LoginComponent(authService, router);
});

Because it needs the params for the Router constructor. Here I saw...

beforeEach(() => addProviders([
    APP_ROUTER_PROVIDERS, // must be first
    {provide: APP_BASE_HREF, useValue: '/'}, // must be second
    {provide: ActivatedRoute, useClass: Mock},
    {provide: Router, useClass: Mock}
]));

But I don't seem to have APP_ROUTER_PROVIDERS or Mock anywhere in my dependencies, so I think it might be stale (or I need dependencies).

How do I mock this out? It doesn't even matter for the test I am working on.


Solution

  • For a simple case you could just create your own mock and provide it by value, for example:

    describe('whatever', () => {
      let mockRouter: any;
      ...
    
      beforeEach(async(() => {
        // create your own mock 
        mockRouter = jasmine.createSpyObj('Router', ['navigate']);
    
        ...
    
        TestBed.configureTestingModule({
          declarations: [LoginComponent],
          providers: [
            // provide it by value
            { provide: Router, useValue: mockRouter },
            ...
          ],
        }).compileComponents();
      }));
    
      ...
    
    }); 
    

    This uses the test bed's dependency injection, rather than trying to "new-up" the class under test.

    For an example in context, see e.g. one of my projects on GitHub.