Test a controller with success() and error ()

后端 未结 3 1122
不知归路
不知归路 2021-01-31 10:07

I\'m trying to work out the best way to unit test success and error callbacks in controllers. I am able to mock out service methods, as long as the controller only uses the defa

3条回答
  •  余生分开走
    2021-01-31 10:51

    Don't mix concerns!

    Using $httpBackend inside a controller is a bad Idea since you are mixing concerns inside your Test. Whether you retrieve data from an Endpoint or not is not a concern of the Controller, is a concern of the DataService you are calling.

    You can see this more clearly if you change the Endpoint Url inside the service you will then have to modify both tests: the service Test and the Controller Test.

    Also as previously mentioned, the use of success and error are syntactic sugar and we should stick to the use of then and catch. But in reality you may find yourself in the need of testing "legacy" code. So for that I'm using this function:

    function generatePromiseMock(resolve, reject) {
        var promise;
        if(resolve) {
            promise = q.when({data: resolve});
        } else if (reject){
            promise = q.reject({data: reject});
        } else {
            throw new Error('You need to provide an argument');
        }
        promise.success = function(fn){
            return q.when(fn(resolve));
        };
        promise.error = function(fn) {
            return q.when(fn(reject));
        };
        return promise;
    }
    

    By calling this function you will get a true promise that respond to then and catch methods when you need to and will also work for the success or error callbacks. Note that the success and error returns a promise itself so it will work with chained then methods.

    (NOTE: On the 4th and 6th line the function returns resolve and reject values inside the data property of an object. This is to mock the Behavior of $http since it returns the data, http Status etc.)

提交回复
热议问题