angularunit-testingkarma-runneraws-amplifyaws-amplify-sdk-js

How to mock AWS amplify methods in Angular unit testing


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.


Solution

  • 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();
    });