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?
Because you are using
ng-mocks
and you want to mock all dependencies, such asRouter
, you can useng-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: