我需要什么?
- 测试,如果在移动的设备电容器
App Plugin
上,则调用removeAllListeners()
函数。
我的应用程序组件中包含的内容:
ngOnDestroy(): void {
if (Capacitor.isNativePlatform()) {
App.removeAllListeners();
}
this.destroy$.next();
this.destroy$.complete();
}
我在单元测试中的做法
按照https://capacitorjs.com/docs/guides/mocking-plugins中的步骤,我创建了mock文件夹,并添加了我在AppComponent中使用的函数
然后我尝试实现测试:
describe('test ngOnDestroy', () => {
beforeEach(fakeAsync(() => {
spyOn(App, 'removeAllListeners');
(App.removeAllListeners as any).and.returnValue(Promise.resolve());
fixture.detectChanges();
fixture.whenStable();
}));
it('should call 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 call 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();
}));
});
日志中的错误
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)
更新日期:
第二次测试成功!
谁能给予我一个正确的方向,它应该如何正确地进行测试?
谢谢你,谢谢你
1条答案
按热度按时间7cjasjjr1#
要使第一个测试用例正常工作,您需要创建一个App.ts模拟文件和“removeAllListeners”函数上的spyOn。
示例:
App.ts
现在在规格文件中
您可以找到为电容器插件here创建模拟的文档