How to use Jest to write a unit test for canActivate Angular guards

1k Views Asked by At

I want to use Jest instead of jasmine to write a unit test for my angular app.

a jest unit test for guard servcie for the mehtod canActivate.

My question is, how to mock the router?

describe('TestServiceGuard', () => {
  let service: testServiceGuard;
  let router: Router;

  beforeEach(() => {
    return MockBuilder(TestServiceGuard, TestModule)
      .mock(TranslateService, {
        instant: (value) => value,
      })
      .mock(Router)
  });

  it('should be created', () => {
    mockCurrentData(data);
    const fixture = MockRender
  
  });

  //this mehtod mock a servcie, which will be called in method canActivate.
  function mockCurrentData(fleet: Fleet): jest.Mock {
    return MockInstance(<the other servcie>, 'testData', jest.fn(), 'get') //
      .mockReturnValue(of(data));
  }

 // I just wannt to mock Router, but I do not know how? 
  function mockRouter(){
    const router = new Mockr
  }

  //then
  function rediretToExpectedSite(){
    expect();
  }

});

I have also see some example such as

it('should navigate to home for a logged out user', () => {
  authService = { isLoggedIn: () => false };
  router = new MockRouter();
  authGuard = new AuthGuard(authService, router);
  spyOn(router, 'navigate');

  expect(authGuard.canActivate()).toEqual(false);
  expect(router.navigate).toHaveBeenCalledWith(['/']);
});

but in my jest test there is no MockRouter.

any solutions?

1

There are 1 best solutions below

0
On

Because you are using ng-mocks and you want to mock all dependencies, such as Router, you can use ng-mocks documentation how to test a provider. It simply explains how to mock all dependencies of your provider: the guard.

Based on the documentation, you test should look like:

describe('TestServiceGuard', () => {
  MockInstance.scope(); // <- add to reset customizations after tests.

  // Simply mock all dependencies apart from the guard.
  // It will automatically mock Router and other services.
  beforeEach(() => {
    return MockBuilder(TestServiceGuard, TestModule)
      .mock(TranslateService, {
        instant: (value) => value,
      });
  });

  it('should be created', () => {
    MockInstance(TheOtherService, 'testData', jest.fn(), 'get')
      .mockReturnValue(of(data));

    const fixture = MockRender(TestServiceGuard);
    const service = fixture.point.componentInstance;
  
    // assertions
  });
});