Mocking $modal in AngularJS unit tests

前端 未结 4 1352
你的背包
你的背包 2020-11-27 11:30

I\'m writing a unit test for a controller that fires up a $modal and uses the promise returned to execute some logic. I can test the parent controller that fire

4条回答
  •  粉色の甜心
    2020-11-27 12:02

    To add to Brant's answer, here is a slightly improved mock that will let you handle some other scenarios.

    var fakeModal = {
        result: {
            then: function (confirmCallback, cancelCallback) {
                this.confirmCallBack = confirmCallback;
                this.cancelCallback = cancelCallback;
                return this;
            },
            catch: function (cancelCallback) {
                this.cancelCallback = cancelCallback;
                return this;
            },
            finally: function (finallyCallback) {
                this.finallyCallback = finallyCallback;
                return this;
            }
        },
        close: function (item) {
            this.result.confirmCallBack(item);
        },
        dismiss: function (item) {
            this.result.cancelCallback(item);
        },
        finally: function () {
            this.result.finallyCallback();
        }
    };
    

    This will allow the mock to handle situations where...

    You use the modal with the .then(), .catch() and .finally() handler style instead passing 2 functions (successCallback, errorCallback) to a .then(), for example:

    modalInstance
        .result
        .then(function () {
            // close hander
        })
        .catch(function () {
            // dismiss handler
        })
        .finally(function () {
            // finally handler
        });
    

提交回复
热议问题