jeudi 2 juillet 2020

Ionic unit tests

I am new to ionic and still learning to write test cases. I have a simple page with a button that on click triggers a Cordova plugin function. The code for button click and plugin call service is as below

Home.ts

import { Component } from '@angular/core';
import { PluginService } from '../plugin.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  public isRecievedData = false;
  public reportData: any;

  constructor(public pluginService: PluginService) { }

  startPluginClicked() {
    this.pluginService.startPuginSession()
      .then((data) => {
        this.isRecievedData = true;
        this.reportData = data;
        console.log("** New report data **")
      }).catch((error) => console.error(error))
  }
}

PluginService

import { Injectable } from '@angular/core';
import { cordova, IonicNativePlugin } from '@ionic-native/core';
@Injectable()

export class PluginService extends IonicNativePlugin {
  static pluginName = 'pluginName';
  static plugin = 'cordova-plugin-pluginName';
  static pluginRef = 'Plugin';
  static repo = 'https://github.com/Plugin.git';
  static platforms = ['iOS']

  startPuginSession(): Promise<any> {
    const x = cordova(this, 'startPuginSession', {}, [])
    return x;
  }
}

home.page.spec

fit('should call startPluginSession on button click', async(() => {
    spyOn(component, 'startPluginClicked');
    let button = fixture.debugElement.nativeElement.querySelector('ion-button');
    button.click();
    fixture.whenStable().then(() => {
      expect(component.startPluginClicked).toHaveBeenCalled();
    });
  }));

  fit('some thing should happen when we do some thing', () => {

    let testPromise = new Promise((resolve) => {
      component.binahService.startPluginSession();
    });

    testPromise.then((result) => {
      component.isRecievedData = true;
    });
    expect(component.isRecievedData).toBe(true);
  });

  fit('Should trigger plugin session', () => {
    component.binahService.startPluginSession().then(() => {
      expect(component.isRecievedData).toBe(true);
    });
  });

Plugin.service.spec

 fit('should present alert', done => {
    const spy = spyOn(service, 'startPluginSession');
    service.startPluginSession().then(() => {
      expect(spy).toHaveBeenCalled();
      done();
    });
  });

The tests that I have written are failing. Can someone please help with the correct test cases with full code coverage. Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire