I decided to write a unit test for the alert present function that gets triggered after creating an alert. This is what my code looks like.
it('should call attempt To call alert present', async () => {
const alert = {
header: 'Permission Required',
cssClass: 'alertStyle',
message:
'Camera permission is required to scan QR codes. You can allow this permission in Settings.',
buttons: ['Dismiss'],
} as HTMLIonAlertElement;
const alertControllerStub = jasmine.createSpyObj('AlertController', ['create']);
await component.displayBarcodeError();
expect(alertControllerStub.create).toHaveBeenCalledTimes(1);
expect(alertControllerStub.create).toHaveBeenCalledWith(alert);
});
This test is specifically targeting the following function:
async displayBarcodeError() {
const alert = await this.alertController.create({
header: 'Permission Required',
cssClass: 'alertStyle',
message: this.translations.msg_camera,
buttons: ['Dismiss'],
});
await alert.present();
}
Aside from testing the above function, I wanted to ensure the correct execution of await alert.present();
. Can you assist me by identifying why the code fails to work or provide a successful test?
Upon running the test, I encountered the error message below:
Expected spy AlertController.create to have been called once. It was called 0 times.
Error: Expected spy AlertController.create to have been called once. It was called 0 times.
at <Jasmine>
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/pages/home/home.page.spec.ts:278:40)
at Generator.next (<anonymous>)
at asyncGeneratorStep (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3:1)
I have diligently followed the code structure mentioned above and seek guidance on how to turn it into a functional test.