I have created a simple snackbar with the following code:
app.component.ts:
ngOnInit(){
this.dataService.valueChanges.pipe(
filter((data) => data === true),
switchMap(() => {
const snackBarRef = this.matSnackBar.open(
'A new value updated',
'OK',
{
duration: 3000
}
);
return snackBarRef.onAction();
})
)
.subscribe(() => {
this.window.location.reload();
});
}
app.component.spec.ts (Including mock data for service)
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let matSnackBarSpy: jasmine.SpyObj<MatSnackBar>;
let a = "";
let b = "";
let c = "";
const mockDataService = {
valueChanges: of(true)
};
beforeEach(async(() => {
TestBed.configureTestingModule({
a = "Test";
b = "X";
c = "suc";
matSnackBarSpy = TestBed.get<MatSnackBar>(MatSnackBar);
})
}))
describe('#ngOnInit()', () => {
it('should call MatSnackBar.open()', async(done: DoneFn) => {
const error = new HttpErrorResponse({ error: 'Some error' });
component.ngOnInit();
expect(mockDataService.valueChanges).toBeTruthy();
expect(matSnackBarSpy.open(a,b,c)).toBeTruthy();
done();
});
});
})
data.service.ts
import { Observable } from 'rxjs';
export class DataService {
valueChanges: Observable<boolean>;
}
Explanation:
I have a service with a property
valueChanges
of typeObservable<boolean>
.In the
component.ts
, I receive boolean valuetrue
after the value change and the snackbar opens successfully.Currently, I am working on implementing test cases in
component.spec.ts
,expect(mockDataService.valueChanges).toBeTruthy(); expect(matSnackBarSpy.open(a,b,c)).toBeTruthy();
Although the tests are passing, I consistently see a warning in Chrome as depicted below.
https://i.sstatic.net/6SXJo.png
- Despite referencing Mocking MatSnackBar in Angular 8 & Jasmine, I am unable to resolve the issue.
Requirement: I aim to cover all the tests that currently show warnings indicating they are not covered, as displayed in the image above.
Even though the test cases pass, the test coverage report still shows function not covered and statement not covered warnings when accessing index.html
of the component.