嘲笑$ stage.go过渡

时间:2016-04-12 15:25:17

标签: angularjs angular-ui-router jasmine

我有一个带有activate()方法的控制器:

function CustomerController(customerFactory, $state, $stateParams) {
    var vm = this;

    vm.getCustomer = getCustomer;

    activate();

    function activate() {
        if($state.is('customer-view')) vm.getCustomer($stateParams.id);
    }

    function getCustomer(id) {
        return customerFactory.getCustomer(id)
            .then(getCustomerComplete)
            .catch(getCustomerFailed);

        function getCustomerComplete(response) {
            return vm.customer = response;
        }

        function getCustomerFailed(error) {
            return vm.error = error;
        }
    }
}

我想使用jasmine测试$state.go('customer-view', {id: 1})已调用getCustomer(id)函数。

这是我的测试:

it("should be called", inject(function($state) {
    spyOn(vm, 'getCustomer');
    $state.go('customer-view', {id: 1});
    expect(vm.getCustomer).toHaveBeenCalledTimes(1);
}));

测试返回"预期的间谍getCustomer被调用一次。它被称为0次。"

PS:上面的代码正在运行,我只是不知道如何测试它。

编辑:

这是我的spec文件的一个更大的例子:

describe("app.customers controller", function () {

    var $controller, customers, deferred, customerFactoryMock, vm, $rootScope, $q;

    beforeEach(function () {
        module('app.customers');
    });

    beforeEach(inject(function (_$rootScope_, _$controller_, _$q_, _customerFactory_) {
        customerFactoryMock = _customerFactory_;
        $controller = _$controller_;
        vm = $controller("CustomerController", {customerFactory: customerFactoryMock});
        $q = _$q_;
        deferred = $q.defer();
        $rootScope = _$rootScope_;
        customers = [{"id": 1}, {"id": 2}];
    }));

    describe("getCustomer(id)", function () {
        it("should call the factory method", function () {
            spyOn(customerFactoryMock, 'getCustomer').and.returnValue(deferred.promise);
            vm.getCustomer(1);
            expect(customerFactoryMock.getCustomer).toHaveBeenCalledTimes(1);
        });

        it("should be called", inject(function($state) {
            spyOn(vm, 'getCustomer');
            $state.go('customer-view', {id: 1});
            expect(vm.getCustomer).toHaveBeenCalledTimes(1);
        }));

        it("should have a customer on resolved", function () {
            spyOn(customerFactoryMock, 'getCustomer').and.returnValue(deferred.promise);
            deferred.resolve({"id": 1});
            vm.getCustomer(1);
            $rootScope.$digest();
            expect(vm.customer).toBeDefined();
            expect(vm.customer.id).toEqual(1);
        });

        it("should return an error message on reject", function () {
            spyOn(customerFactoryMock, 'getCustomer').and.returnValue(deferred.promise);
            deferred.reject('this is a reason');
            vm.getCustomer();
            $rootScope.$digest();
            expect(vm.error).toBeDefined();
            expect(vm.error).toBe('this is a reason');
        });
    });
});

0 个答案:

没有答案