vendredi 9 septembre 2016

how to test ecmascript6 or angular constructor methods and variables with sinon js

Hello am a newbie in SinonJS am trying to test constructor methods but am stuck midway for reference please check below codes:

Problem: unable to test function init on constructor any help would be appreciated

JS

export class ApplyController {

  constructor(homeApiService, userAlertsService, $log, $translate) {
    'ngInject';

    // local vars
    this.userEmail = "";
    this.reason = "";
    this.requesting = false;
    this.requested = false;

    //angular dependancy
    this.$log = $log;
    this.translate = $translate;

    //app dependancy
    this.homeApiService = homeApiService;
    this.userAlertsService = userAlertsService;

    //init functions
    this.initTranslations();
  }

  initTranslations() {
    let $this = this;

    this.translate(['COMMON.AUTH.COULD_NOT_REQUEST_EARLY_ACCESS']).then(function (translations) {
       $this.couldNotRequestEarlyAccess = translations['COMMON.AUTH.COULD_NOT_REQUEST_EARLY_ACCESS'];
    }, function (translationIds) {
       $this.couldNotRequestEarlyAccess = translationIds.couldNotRequestEarlyAccess;
    });
  }

  requestEarlyAccess() {
    this.requesting = true;
    this.homeApiService.requestForEarlyAccess(this.userEmail, this.reason)
      .then((data) => {
        if (data.success) {
          this.requested = true;
        }
        this.userEmail = "";
        this.reason = "";
        this.requesting = false;
      }, (error) => {
        this.userAlertsService.showAlertToast(this.couldNotRequestEarlyAccess);
        this.$log.error("Error while requesting early access", error);
        this.requesting = false;
      });
  }
}

Test case file

describe("only constructor", () => {

  let initSpy;

  beforeEach(() => {
    initSpy = sinon.spy(controller, "initTranslations");
  });

  afterEach(() => {
    initSpy.reset();
  });


  it('#should check constructor methods', sinon.test(() => {

    expect(controller.userEmail).to.equal("");
    expect(controller.reason).to.equal("");
    expect(controller.requesting).to.eq(false);
    expect(controller.requested).to.eq(false);
    // above lines working fine


    console.log(initSpy.callCount);
    // here we got callCount 0 and

    //below lines never tested cause I don't understand
    sinon.assert.calledOnce(initSpy);

  }));

});

Aucun commentaire:

Enregistrer un commentaire