What do I need help with?
- I need to test if the Capacitor
App Plugin
call theremoveAllListeners()
function on mobile devices.
Here is what I have in my App Component:
ngOnDestroy(): void {
if (Capacitor.isNativePlatform()) {
App.removeAllListeners();
}
this.destroy$.next();
this.destroy$.complete();
}
What I am doing in my unit-test:
Following the steps from , I created a mock folder and added functions which I use in my AppComponent.
Then, I try to implement the tests:
describe('testing ngOnDestroy', () => {
beforeEach(fakeAsync(() => {
spyOn(App, 'removeAllListeners');
(App.removeAllListeners as any).and.returnValue(Promise.resolve());
fixture.detectChanges();
fixture.whenStable();
}));
it('should invoke App.removeAllListeners on mobile app', fakeAsync(() => {
spyOn(Capacitor, 'isNativePlatform').and.returnValue(true);
component.ngOnDestroy();
fixture.detectChanges();
fixture.whenStable();
expect(Capacitor.isNativePlatform()).toBeTrue();
// throw an error:
// > Error: Expected spy removeAllListeners to have been called once. It was called 0 times.
// expect(App.removeAllListeners).toHaveBeenCalledTimes(1);
expect(App.removeAllListeners).toHaveBeenCalled();
}));
it('should not invoke App.removeAllListeners on web app', fakeAsync(() => {
spyOn(Capacitor, 'isNativePlatform').and.returnValue(false);
component.ngOnDestroy();
fixture.detectChanges();
fixture.whenStable();
expect(Capacitor.isNativePlatform()).toBeFalse();
expect(App.removeAllListeners).not.toHaveBeenCalled();
}));
});
Errors in the logs:
Error: Expected spy removeAllListeners to have been called.
at <Jasmine>
at UserContext.apply (src/app/app.component.spec.ts:120:38)
at UserContext.fakeAsyncFn (node_modules/zone.js/dist/zone-testing.js:2046:34)
at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:400:1)
Update:
The second test was successful!
Could someone point me in the right direction on how to correctly test this?
Thank you!