使用templateUrl Karma错误的指令

时间:2018-06-02 00:17:28

标签: angularjs angularjs-directive jasmine karma-jasmine

我在测试具有带Karma的TemplateUrl的指令时遇到问题。 每当我去测试时我都会收到错误:意外的请求:GET views / templates / directives / input.html

这是我的指令

的代码
app.directive('destinationDirective', function(){
    var controller = function($http, $rootScope, $scope) {

        $scope.getWeather = function(user) {
            $http.get("http://api.openweathermap.org/data/2.5/weather?q="+user.localization+"&appid="+$scope.apiKey).then(
                function successCallBack(res) {
                    if (res.data.weather) {
                        user.weather = {};
                        user.weather.main = res.data.weather[0].main;
                        user.weather.temp = $scope.convertKtoC(res.data.main.temp);
                    } else {
                        $rootScope.message = "Localization not found";
                    }
                },
                function errorCallBack(error) {
                    if(error.data.cod == "404") {
                        $rootScope.message = "City not found"
                    } else {
                        $rootScope.message = "Server error";
                    }
                });
        };

        $scope.convertKtoC = function(temp) {
            return Math.round(temp - 273);
        };
    }

    return {
        scope: {
            user: '=',
            apiKey: '=',
            onRemove: '&'
        },
        controller: controller,
        controllerAs: 'VM',
        templateUrl: 'views/templates/directives/input.html'
    }
});

我的.spec

describe('Teste do ModalController', function() {
    var ctrl, scope, rootscope, httpBackend, timeout, rootScope;

    //Injeta o modulo toda vez que for executar um spec
    beforeEach(module('APP'));

    //Injeta o controller sempre que for fazer um teste
    beforeEach(inject(function(_$controller_, _$rootScope_, _$httpBackend_, _$timeout_) {
        rootScope = _$rootScope_;
        scope = _$rootScope_.$new();
        httpBackend = _$httpBackend_;
        timeout = _$timeout_;
        ctrl = _$controller_('ModalController', {
            $scope: scope
        });
    }));

    // beforeEach(module('ngTemplatePHP'));
    // beforeEach(module('ngTemplate'));

    afterEach(function() {
        //Verifica se todas as expectativas foram feitas
        httpBackend.verifyNoOutstandingExpectation();
        //Verifica se todas as requisições foram feitas
        httpBackend.verifyNoOutstandingRequest();
    });

    describe('Testando destinationDirective', function() {
    var scope, template, httpBackend, isolateScope;
    beforeEach(inject(function($compile, _$rootScope_, $httpBackend) {
        scope = _$rootScope_.$new();
        httpBackend = $httpBackend;

        scope.newUser = {};

        scope.newUser = {
            "name": "Jorge",
            "pass": "iser",
            "localization": "Melbourne"
        };

        scope.apiKey = "xyz";

        var element = angular.element('<div destination-directive user="user" api-key="apiKey" on-remove="remove()"></div>');

        template = $compile(element)(scope);
        //Aplica as alteracores
        scope.$digest();

        //Isola o scope do controller, do scopo do directive
        isolateScope = element.isolateScope();
    }));

    it('devera atualizar o clima de uma localizacao', function() {
        scope.newUser = {
            "name": "Jorge",
            "pass": "iser",
            "localization": "Melbourne"
        };

        // httpBackend simula o backend
        // expectGET faz uma requisição get
        // respond cria o que seria a resposta esperada
        httpBackend.expectGET("http://api.openweathermap.org/data/2.5/weather?q=" + scope.newUser.localization + "&appid=" + scope.apiKey).respond({
            weather: [{
                main: 'Rain',
                detail: 'Light rain'
            }],
            main: {
                temp: 288
            }
        });

        isolateScope.getWeather(scope.newUser);

        httpBackend.flush();

        expect(scope.newUser.weather.main).toBe("Rain");
        expect(scope.newUser.weather.temp).toBe(15);
    });

    it('devera chamar a funcao remove do controller pai', function() {
        scope.removeTest = 1;

        scope.remove = function() {
            scope.removeTest++;
        }

        isolateScope.onRemove();
        expect(scope.removeTest).toBe(2);
    });

    it('devera gerar o HTML corretamente', function() {
        var templateAsHtml = template.html();

        expect(templateAsHtml).toContain('Melbourne');
    });
    });
});

我的karma.conf.js

module.exports = function(config) {
  config.set({

    basePath: '',

    frameworks: ['jasmine'],

    files: [
    'node_modules/angular/angular.js',
    'node_modules/angular-sanitize/angular-sanitize.min.js',
    'node_modules/angular-mocks/angular-mocks.js',
    'node_modules/sweetalert/dist/sweetalert.min.js',
    'node_modules/karma-ng-html2js-preprocessor/lib/html2js.js',
    'node_modules/karma-ng-php2js-preprocessor/lib/php2js.js',

    'public/ngDS/app.ng.js',
    'public/ngDS/**.js',
    'public/ngDS/**/**.js',

    'public/assets/js/app.ng.js',
    'public/assets/js/**/**.js',
    'public/views/**/**.php',
    'public/views/**/**.html'
    ],

    plugins: [
        'karma-jasmine',
        'karma-spec-reporter',
        'karma-chrome-launcher',
        'karma-ng-html2js-preprocessor',
        'karma-ng-php2js-preprocessor'
    ],

    exclude: [
    ],

    preprocessors: {
    'public/views/templates/**/**.html': ['ng-html2js'],
    'public/views/templates/**/**.php': ['ng-php2js']
    },

    ngHtml2JsPreprocessor : {
     stripPrefix :  'public/',
     moduleName :  'ngTemplates'
   },

    ngPhp2JsPreprocessor: {
          stripPrefix: 'public/',
          stripSuffix: '.ext',
          moduleName: 'ngTemplatePHP',
          phpBin: '/php'
      },

    reporters: ['spec'],

    port: 9876,


    colors: true,

    logLevel: config.LOG_INFO,


    autoWatch: true,

    browsers: ['Chrome'],

    singleRun: false,

    concurrency: Infinity
  });
}

我一直在找一些时间但找不到解决方案。

1 个答案:

答案 0 :(得分:0)

.spec 文件中,您需要注入 ngTemplate 模块,该模块包含您使用 ngHtml2JsPreprocessor 创建的html和php模板在 karma.conf.js 文件中:

...
//Injeta o modulo toda vez que for executar um spec
  beforeEach(module('APP'));
  beforeEach(module('ngTemplates'));
...

使用基于您的文件的工作示例检查this存储库。

相关问题