I want to test with jasmine a snackbar service. More specific, I'm testing the following two cases:
- That the service is created
- The method inside it to be called
snackbar.service
import { Injectable, NgZone } from '@angular/core';
import { MatSnackBar } from '@angular/material';
@Injectable({
providedIn: 'root'
})
export class SnackbarService {
constructor(
public snackBar: MatSnackBar,
private zone: NgZone
) { }
public open(message, action, duration = 1000) {
this.zone.run(() => {
this.snackBar.open(message, action, { duration });
})
}
}
snackbar.service.spec
import { TestBed } from '@angular/core/testing';
import { SnackbarService } from './snackbar.service';
describe('SnackbarService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: SnackbarService = TestBed.get(SnackbarService);
expect(service).toBeTruthy();
});
it('should call open()', () => {
const service: SnackbarService = TestBed.get(SnackbarService);
const spy = spyOn(service, 'open');
service.open('Hello', 'X', 1000);
expect(spy).toHaveBeenCalled();
})
});
After running the tests, Karma gives me the following errors:
- SnackbarService > should call open() NullInjectorError: StaticInjectorError(DynamicTestModule)[MatSnackBar]: StaticInjectorError(Platform: core)[MatSnackBar]: NullInjectorError: No provider for MatSnackBar!
- SnackbarService > should be created NullInjectorError: StaticInjectorError(DynamicTestModule)[MatSnackBar]: StaticInjectorError(Platform: core)[MatSnackBar]: NullInjectorError: No provider for MatSnackBar!
Any ideas on how should I fix this issue?
Thanks!