'How to write unit test for a service having breakpoint observer?
I have a service having a breakpoint observer. But how we can trigger window resize event for breakpoint observer to cover all branch and lines.
export class BreakPointService {
isSmallDevice ;
constructor(private breakpointObserver: BreakpointObserver) {
this.breakpointObserver.observe([`(max-width: 899px)`,
`(min-width: 900px)`])
.subscribe(result => {
if (result.matches) {
if (result.breakpoints[`(max-width: 899px)`]) {
this.isSmallDevice = true;
}
if (result.breakpoints[`(min-width: 900px)`]) {
this.isSmallDevice = false;
}
}
});
}
}
Solution 1:[1]
I have had to create a test in a presentational component recently, where the responsive is used in a logical way.
For this I have created methods outside the constructor or ngOnInit, which I test independently. And regarding the module I have injected it in this way TestBed.inject(BreakpointObserver);
This was my scheme:
fdescribe('yourComponent', () => {
let component: yourComponent;
let fixture: ComponentFixture<yourComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
schemas: [
CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA
],
declarations: [ yourComponent ],
providers: [],
imports: [ yourModule],
})
.compileComponents();
TestBed.inject(BreakpointObserver); // <------ inject
});
beforeEach(() => {
fixture = TestBed.createComponent(yourComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('Can load instance', () => {
expect(component).toBeTruthy();
});
it('Test for the method how do somthing', () => {
// <---------- your test
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hamada |