Mocha单元测试一个指令,其中在链接函数内部调用的函数返回一个promise

时间:2015-07-28 06:28:05

标签: javascript angularjs unit-testing mocha karma-runner

我的角度指令看起来像这样。

angular.module('directives').directive(“testDirective”,function($q,testService){
    return {
        restrict:'A',
        scope:{
           test:'@'
        },
        controller: function($scope, $element){

        },
        templateUrl:'testTemplate.html',
        link:function(scope, element, attrs){
           scope.loadTests = function(){
                var deferred = $q.defer();
                testService.get('/test_url').success(function (data, status, headers, config) {
                    if (status == 200) {
                       scope.dataHolderId = data.id;
                       deferred.resolve({});
                    }
                });
                return deferred.promise;
           };
           scope.loadTests();
        }
  }
});

我的mocha测试代码是以这种方式构建的。

describe('directive should be rendered', function() {
    var httpBackend, $compile, $rootScope, $templateCache, html, scope, element;
    var q;
    var testService;
    var innerScope;
    var deferred;

    beforeEach(module('services'));
    beforeEach(module('directives'));
    beforeEach(module('htmlTemplates'));

    beforeEach(inject(function(_$httpBackend_, _$compile_, _$rootScope_,$q,_testService_) {
        httpBackend = _$httpBackend_;
        $compile = _$compile_;
        q = $q;
        $rootScope = _$rootScope_;
        deferred = $q.defer();
        testService = _testService_;
    }));

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    it("should test function with test service ", function() {
        var scope = $rootScope.$new();
        deferred.resolve();
        var html = '<div test-directive test="Hello"></div>';
        var element = angular.element(html);
        var expectedData = {id:23423};
        httpBackend.when('GET', '/test_url').respond(200, { payload: expectedData});
        element = $compile(element)(scope);
        scope.$digest();
        innerScope = element.isolateScope();

        expect(innerScope.dataHolderId).to.equal(23423);
        //done();
        httpBackend.flush();
    });
});

我的断言因未定义的错误而失败。我也嘲笑了我的延迟对象和http调用。不确定断言失败的原因。这也在异步模式下失败(使用完成回调)

0 个答案:

没有答案