Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing ModalController Ionic 3 spyOn method not called

I am trying to test a method that launch a modal, has anybody done this before, can someone perhaps point me in the right direction?? I have written the following test suite.

describe('bdb modal provider test suite', () => {

let bdbModal: BdbModalProvider;
let modal: Modal;
let modalCtrl: ModalController;

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
            BdbModalProvider,
            { provide: ModalController, useClass: ModalControllerMock }
        ]
    });
    bdbModal = TestBed.get(BdbModalProvider);
    modalCtrl = TestBed.get(ModalController);
});

beforeEach(() => {
    modal = modalCtrl.create('ModalErrorPage', {});
});

it('should launch error modal', () => {
    spyOn(modal, 'present');
    bdbModal.launchErrModal('testing', 'error modal', 'OK');
    expect(modal.present).toHaveBeenCalled();
});
});

this is the error log:

should launch error modal bdb modal provider test suite Expected spy present to have been called. at UserContext. (webpack:///src/providers/bdb-modal/bdb-modal.spec.ts:31:30 <- test-config/karma-test-shim.js:140545:31)

like image 294
Jhonycage Avatar asked Mar 07 '23 00:03

Jhonycage


1 Answers

1. Create Spy of modal and modal controller.

    modalSpy = jasmine.createSpyObj('Modal', ['present']);
    modalCtrlSpy = jasmine.createSpyObj('ModalController', ['create']);
    modalCtrlSpy.create.and.callFake(function () {
        return modalSpy;
    });


2. Add it's entry in test bed as below:

TestBed.configureTestingModule({

      declarations: [
        ..............
      ],

      providers: [
        ..............

        {
          provide: ModalController,
          useValue: modalCtrlSpy
        }
        ..............
      ],

      imports: [
        ............
      ]

    }).compileComponents();

  }));


3. Test case should be like below:

it('#display() should display modal', () => {
    .........
    expect(modalSpy.present).toHaveBeenCalled(); 
    .........
});
like image 143
Yuvraj Patil Avatar answered Mar 14 '23 09:03

Yuvraj Patil