I have a simple notifications module that uses material's snack bar while listening on an Ngrx Selector. I dont have any components and work is done in the module's constructor so the consumer only needs to import the module and then dispatch a new notification.
@NgModule({
declarations: [],
imports: [
CommonModule,
StoreModule.forFeature(
NOTIFICATIONS_STATE_FEATURE_KEY,
notificationsModuleReducer
),
MatSnackBarModule,
],
})
export class NotificationsModule {
private store = inject(Store);
private snackBar = inject(MatSnackBar);
constructor() {
this.store
.select(selectNotifications)
.pipe(debounceTime(1000))
.subscribe((notification) => {
if (notification) {
const config = new MatSnackBarConfig();
if (!notification.dontClose) {
config.duration = 3000;
}
config.panelClass = [`${notification.kind}-notification`];
this.snackBar.open(
`${notification.kind.toUpperCase()}: ${notification.message}`,
'X',
config
);
}
});
}
}
I need to write a test for coveragerage purpopses and I'm having trouble. I usually use NgMocks but I can live without it. I've tried to implement the method in Angular 5 testing code in module constructor but I continually get a null injector error for MatSnackBar
.
it('opens the snack bar', () => {
TestBed.configureTestingModule({
imports: [NotificationsModule, MatSnackBarModule],
providers: [provideMockStore()],
})
.compileComponents()
.then(() => {
const snackBar = TestBed.inject(MatSnackBar);
const snackBarSpy = spyOn(snackBar, 'open').and.callThrough();
const testConfig = new MatSnackBarConfig();
testConfig.panelClass = [
`${notificationTestState.notification?.kind}-notification`,
];
expect(snackBarSpy).toHaveBeenCalledWith(
notificationTestState.notification?.message as string,
'X',
testConfig
);
});
});
Error:
Unhandled promise rejection: NullInjectorError: R3InjectorError(CompilerModule)[MatSnackBar -> MatSnackBar]: NullInjectorError: No provider for MatSnackBar!
Any ideas?