0

I am trying to unit test inner data in Angular 15 functional guard, see the last condition. Need to make sure the error message appears if user has no license.
How can that be done without public properties/functions? Please help, I am new to functional guards.

TIA, Oleg.

export const isAuthGuardFn: CanActivateFn = (route: ActivatedRouteSnapshot) => {
  return checkUserLogin(route);
}

const checkUserLogin = async (route: ActivatedRouteSnapshot): Promise<boolean> => {
  const msgService = inject(MessageService);
  const _userLoginInfoService = inject(UserLoginInfoService);
  let userLoginInfo = USERLOGININFOEMPTYDATA;

  _userLoginInfoService.retrieveLoginInfo();
  _userLoginInfoService.userLoginInfo$.subscribe(loginInfo => userLoginInfo = loginInfo);

if (!userLoginInfo.licensed) {
    msgService.add({ severity: 'error', summary: 'Error', detail: 'You do not have a license. Please contact your system administrator.' });
  }
user1981152
  • 119
  • 1
  • 1
  • 10
  • You have different types of async mixed up and also you are using the result from an async call in a sychronous manner which will fail every time. `subscribe` is async, equivalent to `promise.then` meaning it is deferred. Your check on `userLoginInfo.licensed` happens outside of that so it will execute before you get your result. Also you are returning a Promise in your signature but you do not actually return a promise in your code and there is no use of async/await. – Igor Aug 15 '23 at 14:48
  • Sorry, this is just a fragment of my functional guard, regarding a function that I want to test (that "if"). Full guard does have more conditions and returns true or false. So how do I get to the userLoginInfo (service) and set/mock that licensed flag in my unit test? And how do I call that guard from my unit test, so checkUserLogin() gets executed? – user1981152 Aug 15 '23 at 19:52
  • See this answer on configuring your test framework: https://stackoverflow.com/a/56251126/1260204 – Igor Aug 15 '23 at 20:06
  • @Igor: Hmm, this is an Angular6 testing component, how is it relevant to my question(s)? Inject the service? Please elaborate. And I am not sure how to invoke that service guard inside unit test. – user1981152 Aug 15 '23 at 21:11

0 Answers0