Issue
I am testing my Ionic 3 application with Jasmine, and I am wondering how to mock an AlertController that creates a confirmation alert.
The function that creates the confirmation alert is the following:
pressedButton:string="";
myAlert() {
let confirm = this.alerCtrl.create({
title: 'Title',
message: 'Some message here',
buttons: [
{
text: 'No',
handler: () => {
this.pressedButton = 'No';
}
},
{
text: 'Yes',
handler: () => {
this.pressedButton = 'Yes';
}
}]
});
confirm.present()
}
Basically, what I want is to create a mock for the AlertController that simulates, for example, the user pressing the "yes" button so that I can test the code inside the Yes button handler. Following my unit test.
beforeEach(() => {
fixture = TestBed.createComponent(MyPage);
comp = fixture.componentInstance;
});
it('should set pressedButton to "Yes" when the user press the "Yes" button', () => {
comp.myAlert(); //I want a mock that simulates the Yes button being pressed
expect(comp.pressedButton).toEqual('Yes');
});
I have looked to ionic3-mocks (link below), but I can't figure out how to force button actions inside an alert. https://www.npmjs.com/package/ionic3-mocks
Solution
I'm not entirely familiar with ionic, but in the end, this is all just JavaScript and HTML. What you need to do is grab the DOM element corresponding to the button you want to click and then invoke the click method.
Here is what might work.
Add ids to all of your alert controller buttons, like this:
let confirm = this.alerCtrl.create({
title: 'Title',
message: 'Some message here',
buttons: [
{
text: 'No',
handler: () => {
this.pressedButton = 'No';
},
id: 'no-alert'
},
{
text: 'Yes',
handler: () => {
this.pressedButton = 'Yes';
},
id: 'yes-alert'
}]
});
confirm.present()
Then in your test, grab the button element:
let yesButton = document.getElementById('yes-alert');
yesButton.click();
...continue the test...
Update It is better to test the controller itself and make sure that all the actions are wired up properly, but if that's not possible, you can just test the handler code directly.
Something like this would work:
export const yesHandler = () => ...
export const noHandler = () => ...
pressedButton:string="";
myAlert() {
let confirm = this.alerCtrl.create({
title: 'Title',
message: 'Some message here',
buttons: [
{
text: 'No',
handler: noHandler
},
{
text: 'Yes',
handler: yesHandler
}]
});
confirm.present()
}
And then you can test these handlers directly in your tests.
Answered By - Andrew Eisenberg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.