Search code examples
angularkarma-jasmineaws-amplify

How to prevent "‘amplify-authenticator’ is not a known element" error in unit tests when using Amplify UI Components


I am using the Amplify UI Components for Angular V 10. When unit-testing my application, I receive the following error:

ERROR: ‘amplify-authenticator’ is not a known element

In order to prevent this error, I'm importing the AmplifyUIAngularModule in the testing configuration of the component:

import { AmplifyUIAngularModule } from '@aws-amplify/ui-angular';

beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        AmplifyUIAngularModule
      ]
    })
})

This resolves the first error, but triggers another one:

Error: Amplify has not been configured correctly.
The configuration object is missing required auth properties.
Did you run amplify push after adding auth via amplify add auth?
See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information

So obviously it’s telling me that the AmplifyUIAngularModule can’t be initialized without a config. I tried to add it, although it feels wrong, as the component should not connect in a unit test, but be mocked:

Amplify.configure({
    Auth: {
      ....
    },
  });

This indeed resolves the error, but when karma/jasmine tries to connect to headless chrome for testing, there is a timeout. I suspect the amplify stuff is trying to connect indeed, which can’t be the way to go in a unit test.

There are various threads on SO about how to mock a AWS/Amplify call, but I can't find anything about how to prevent the missing amplify-authenticator dependency.


Solution

  • Like Mike S. correctly pointed out, mocking the whole component works just fine:

    @Component({
      selector: 'amplify-authenticator',
      template: '',
    })
    class AmplifyAuthenticatorMock {}
    
    beforeEach(async () => {
        await TestBed.configureTestingModule({
          declarations: [
            AmplifyAuthenticatorMock,
            AppComponent,
          ],
        }).compileComponents();
      });