My Angular 8 application utilizes the Angular Material MatSnackBar
, and I am currently in the process of testing whether the open()
method of this class is triggered. The invocation of open()
happens within an NgRx store selector as shown below:
ngOnInit() {
this.store.dispatch(fromStore.getFeaturedPlaylists());
this.subscription = this.store.pipe(
select(fromStore.selectError),
filter(err => !!err),
switchMap((err) => this.snackBar.open(
`Error: ${err.message}`,
'Try again',
{duration: 5000}).afterDismissed())
).subscribe(() => this.store.dispatch(fromStore.getFeaturedPlaylists()));
}
The segment of my test related to this scenario is presented here:
describe('FeaturedPlaylistsComponent', () => {
let component: FeaturedPlaylistsComponent;
let fixture: ComponentFixture<FeaturedPlaylistsComponent>;
let matSnackBarSpy: jasmine.SpyObj<MatSnackBar>;
beforeEach(async(() => {
const spy = jasmine.createSpyObj('MatSnackBar', ['open']);
TestBed.configureTestingModule({
declarations: [
// other declarations here
FeaturedPlaylistsComponent
],
providers: [
// other providers here
{provide: MatSnackBar, useValue: spy}
]
})
.compileComponents();
matSnackBarSpy = TestBed.get<MatSnackBar>(MatSnackBar);
}));
beforeEach(() => {
fixture = TestBed.createComponent(FeaturedPlaylistsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
describe('#ngOnInit()', () => { // fails
// lots of other test...
it('should call MatSnackBar.open() on error', () => {
const error = new HttpErrorResponse({error: 'Some error'});
component.ngOnInit();
store.dispatch(fromStore.setError({error}));
expect(matSnackBarSpy.open).toHaveBeenCalled();
});
});
});
I was somewhat surprised by the success of the test confirming the functionality of the ngOnInit()
function, especially given that no tick(5000)
delay was included to account for dialog dismissal.
Moving the open()
call to the beginning of the function resulted in a working
should call MatSnackBar.open() on error
test. This leads me to believe that the issue lies with the placement of the open()
call inside the store selector block.
If anyone can shed light on why the
should dispatch a getFeaturedPlaylists() action on error
test succeeds while the should call MatSnackBar.open() on error
test fails, I would greatly appreciate the insights.