1

I am using AWS cognito, Amplify and Angular 10.

I want a navbar not to be rendered if a user is not logged in:

app.html:

<ng-container *ngIf="isLoggedIn">
  <navbar></navbar>
</ng-container>

app.ts:

constructor() {
  this.checkIfLoggedIn();
}

checkIfLoggedIn() {
  Auth.currentUserInfo().then((userData) => {
    if (userData) {
      this.isLoggedIn = true;
    }
  });
}

This works. However, my unit tests (Karma/Jasmine) throw an error:

Error: Amplify has not been configured correctly.
        The configuration object is missing required auth properties.

This is because I don't know hot to mock Auth.currentUserInfo.then correctly (despite reading various posts about it like this or that).

Attempts:

1) SpyOn

I thought it would be something like spyOn(Auth, 'currentUserInfo').and.returnValue(Promise.resolve(true));

2) Mocking Auth in providers

like suggested in the comments.

import { Auth } from 'aws-amplify';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [AppComponent],
    providers: [
      {
        provide: Auth,
        useValue: { currentUserInfo: () => Promise.resolve('hello') },
      },
    ],
  }).compileComponents();
}

Unfortunately they don't make the error message go away.

user3255061
  • 1,757
  • 1
  • 30
  • 50
  • 1
    Auth is initialized even though you spied on it. Try in providers `{provide: Auth, useValue: { currentUserInfo: () => Promise.resolve(true) }}` – Bojan Kogoj Dec 11 '20 at 11:46
  • Thanks a lot for your help, I appreciate it. Unfortunately this did not work, I updated my question accordingly. – user3255061 Dec 11 '20 at 12:36
  • Have you tried with `useClass: MyClass` instead of useValue? – Lucho Dec 11 '20 at 18:28
  • Yes. That gives an "unreachable" error, like described here: https://stackoverflow.com/questions/62281756/jasmine-angular-9-test-failing-because-unreachable-stack-trace-at-injectablede – user3255061 Dec 14 '20 at 20:19
  • Ok, used it wrong. If I mock a service (see https://stackoverflow.com/a/62284218/3255061), there is no "unreachable", but there is still the "Error: Amplify has not been configured correctly. The configuration object is missing required auth properties." error. – user3255061 Dec 14 '20 at 20:29

1 Answers1

2

Looks like Auth is a global object. Therefore the way with spyOn(Auth, 'currentUserInfo').and.returnValue(Promise.resolve(true)); is the right one, but it should be called before TestBed.configureTestingModule.

const backup: any;

// faking currentUserInfo
beforeEach(() => {
  backup = Auth.currentUserInfo;
  Auth.currentUserInfo = jasmine.createSpy()
    .and.returnValue(Promise.resolve(true));
});

// restoring original function
afterEach(() => {
  Auth.currentUserInfo = backup;
});

// now our test begins
beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [AppComponent],
  }).compileComponents();
});
satanTime
  • 12,631
  • 1
  • 25
  • 73