简体   繁体   中英

Jasmine spy not working on Capacitor Plugin in Ionic App

I'm trying to set up an unit test for an Ionic App. In my specs I have:

it('should not change status bar on browser', async () => {
  spyOn(Plugins.StatusBar, 'setStyle');

  const service: AppService = TestBed.inject(AppService);
  await service.initApp();

  expect(Plugins.StatusBar.setStyle).not.toHaveBeenCalled();
});

But it fails with:

Error: <toHaveBeenCalled> : Expected a spy, but got Function.
    Usage: expect(<spyObj>).toHaveBeenCalled() in node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 5180)
    <Jasmine>
    http://localhost:9876/_karma_webpack_/main.js:1161:112
    <Jasmine>
    fulfilled@http://localhost:9876/_karma_webpack_/main.js:716:62
    run@http://localhost:9876/_karma_webpack_/polyfills.js:3595:53
    http://localhost:9876/_karma_webpack_/polyfills.js:4329:43
    runTask@http://localhost:9876/_karma_webpack_/polyfills.js:3639:61
    drainMicroTaskQueue@http://localhost:9876/_karma_webpack_/polyfills.js:4041:46
    <Jasmine>

I've setup a mock in my project for testing with this same object. Your problem is that you're trying to call spyOn() on an object that isn't a mock.

The following incorporates elements that worked for my tests:

it('should not change status bar on browser', async () => {
  statusBarSpy = jasmine.createSpyObj<StatusBarPlugin>('StatusBar', ['setStyle']);

  const service: AppService = TestBed.inject(AppService);
  await service.initApp();

  expect(statusBarSpy.setStyle).not.toHaveBeenCalled();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM