We're in the process of migrating to using Jest over Karma in our Angular 12 App and are getting an error across the board in our spec files which use Auth0:
Unexpected value 'AuthModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.
Weird part: Our current unit-testing with Karma works like a charm with no errors
Example spec :
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
AuthModule.forRoot(mockAuth0Config),
HttpClientTestingModule
],
declarations: [
MyComponent
]
}).compileComponents();
}));
Auth0's library looks good to me (it's not a component or service, it is indeed a "Module" using the ModuleWithProviders interface:
All of the other issues I've come across are when components or services are imported incorrectly, which is not the case here.
Additionally, AuthModule.forRoot({...}) is used in the imports our app.module.ts just fine and is the basis for using Auth0 with Angular, which all work without issue in production.
The above error only happens when running our existing tests in Jest.
The solution I came to was to bypass Auth0 entirely and create a mock Auth0 module that mimics the same functions and params.
@NgModule({
imports: [],
exports: []
})
export class AuthModuleMock {
/**
* Mock forRoot method
* @param config The optional configuration for the SDK.
*/
static forRoot(config ?: AuthConfig) : ModuleWithProviders<AuthModule> {
return {
ngModule: AuthModule,
providers: [
AuthService,
AuthGuard,
{
provide: AuthConfigService,
useValue: config
},
{
provide : Auth0ClientService,
useFactory: () : any => { return; },
deps : [
AuthClientConfig
]
}
]
};
}
}
This is them imported into the .spec files instead of the AuthModule provided by Auth0
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
AuthModuleMock.forRoot(mockAuth0Config),
HttpClientTestingModule
],
declarations: [
MyComponent
]
}).compileComponents();
}));
Either use preset: jest-preset-angular in jest.config or re-generate those shared libraries/modules with the new setting and move the old source codes to the new generated library.