Mock a class used as property of a service


#1

I am actually developing an Ionic application. In this context, I implemented an AlertService class which has the two following properties:

messageAlert: Alert;
errorAlert: Alert;

The Alert class is the one of the Ionic framework so I don’t have any control on it. My idea was to mock the Alert class by a homemade mock like the following class:

class AlertMock {
    opts:       Object;
    presented:  boolean;

    constructor(opts) {
        this.opts       = opts;
        this.presented  = false;
    }

    present() {
        this.presented  = true;
    }

    dismiss() {
        this.presented  = false;
    }
}

It will allow me to simply test the alert state by checking the value of the presented property.

But how can I indicate to my AlertService that it two Alert properties are of type AlertMock instead? I don’t know if it is even possible. But it seems to me quite basic to be able to mock class like that. Every topic I found talk about mocking service. With DI, it’s very simple to replace a type by another, but is there any mechanism to do it with simple class like Alert of the Ionic framework?


#2

WHy dont ypu extend the AlertController class into your own class (classic inheritance question)?

And dig in the code of AlertController if you beed to know how its done in the framework


#3

I just start to learn how to test an Angular/Ionic application one week ago so I am still learning how to do it.
The reason why I didn’t want to extend Ionic classes is I want to abstract the complexity of these kind of classes.
Indeed, the AlertController needs an instance of an App. But if I have to create an instance of an App to make my tests, we are not talking about isolated\unit testing anymore.