如何正确编写针对路由的角度单元测试

时间:2013-10-20 23:10:03

标签: unit-testing angularjs jasmine karma-runner

所以我有一个模仿href函数的指令,除了我希望它可以用按钮,(比方说我不喜欢css标签)。

app.directive('ngRef', function($location, $timeout){
    linkFn = function(sco,ele,att){
        ele.bind('click', function(){
//            console.log($location);
            $timeout(function(){
                $location.path(att.ngRef);
            }, 0);
        })
    }
    return linkFn;
})

现在我编写一个测试,看看mockLocation是否在点击后被贴到新位置,所以

describe('ngRef', function(){
    var mockLoc, mockTimeout, mockCompile, rootScope;

    beforeEach(function(){
        module('mySite')
        inject(function($injector){
            mockLoc = $injector.get('$location');
            mockTimeout = $injector.get('$timeout');
            mockCompile = $injector.get('$compile');
            rootScope = $injector.get('$rootScope');
        })  
    })

    it('should land on the page of the ngRef attribute on click event', function(){
        var elem = angular.element('<button ng-ref="/contact">Click</button>');
        expect(rootScope.activePage).toBe('HOME');
        mockLoc.path('/home')
        mockCompile(elem)(rootScope.$new())

        elem.trigger('click');
        rootScope.$apply();
        setTimeout(function(){
            console.log(rootScope.activePage);
            expect(mockLoc.path()).toBe('CONTACT');     
        }, 0)
    })
})

但现在我注意到测试总是失败,我的断言有什么问题。

1 个答案:

答案 0 :(得分:0)

假设您使用的是Angular 1.2.0,我认为您需要在测试中加载ngRoute并确保它包含在配置中:

beforeEach(module('ngRoute'));

如果您包含从单元测试中获得的输出错误消息,那将会有所帮助。

相关问题