【问题标题】:how to correctly write angular unit-tests against routing如何正确编写针对路由的角度单元测试
【发布时间】:2013-10-20 23:10:03
【问题描述】:

所以我有一个模仿 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)
    })
})

但现在我注意到它总是无法通过测试,我的断言有什么问题。

【问题讨论】:

    标签: unit-testing angularjs jasmine karma-runner


    【解决方案1】:

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

    beforeEach(module('ngRoute'));
    

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

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      相关资源
      最近更新 更多