咕嘟咕嘟角单元测试指令templateUrl [英] Gulp angular unit testing directive templateUrl

查看:163
本文介绍了咕嘟咕嘟角单元测试指令templateUrl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了互联网等多个职位,但无法找到工作的任何解决方案
我试图写单元测试的指令,并希望从模板缓存服务的HTML文件

我使用咕嘟咕嘟作为构建工具

有关测试的一饮而尽任务看起来像这样

  gulp.task(测试,函数(完成){
    karma.start({
        CONFIGFILE:__目录名称+/+ config.test.karmaconf,
        singleRun:假的
    }完成);
});

karma.conf ,我已经定义

  browserify:{
        调试:真实,
        变换:[['browserify-NG-html2js',{
            模块:'模板',
            延伸:HTML
        }]]
    }

在单元测试中,我声明

  beforeEach(angular.mock.module('模板'));

但接受

 错误:意外的请求:GET路径/要/ some.html
没有更多的要求预期
    在$ httpBackend

我也试过在karma.conf而是利用 preprocessors ngHtml2Js preprocessor ​​无成功。任何人都可以提供解决方案或指向我,我怎么能去有关调试为什么模板不提供?


解决方案

解决方案

有多种方法,你可以去这样做。以下是我如何做到这一点:


  1. 使用吞掉-角templatecache

gulp.task('捆绑常见',函数(){
  返回合并(
    在$ templateCache // Store中的所有HTML文件
    gulp.src([
      APPDIR +'/common/**/*.html
    ])
    .pipe($$。angularTemplatecache({
      根:共同
    }))    //追加一切:指令,测试等。
    gulp.src([
      APPDIR +'/common/**/*.js
    ])
  )
  .pipe($$。CONCAT('common.js'))
  .pipe(gulp.dest(公共/ JS /'));
});

这将输出一个名为 common.js 在它所有的HTML模板和指令。

它看起来有点像这样的:

angular.module(模板)。运行([$ templateCache功能($ templateCache){
$ templateCache.put(通用/一个伟大-eye.html,< D​​IV>无盖,火焰缭绕,2倍和LT; / DIV>中);}]);angular.module(常用).directive('aGreatEye',函数(){
    返回{
        限制:'E',
        更换:真实,
        templateUrl:通用/一个伟大-eye.html
    };
});...

<醇开始=2>

  • karma.conf.js 负荷 common.js

  • 文件:
          ../vendor/jquery/dist/jquery.js',
          ../vendor/angular/angular.js',
          ../vendor/angular-mocks/angular-mocks.js',
          ../public/js/common.js
        ]

    <醇开始=3>

  • 在您的测试文件中引用模板模块:

  • 描述('单元测试的伟大名言',函数(){
      变量$编译,
          $ rootScope;  //加载公共模块,其中包含了指令
      beforeEach(函数(){
        模块('模板');
        模块('共同');
      });  //商店引用$ rootScope和$编译
      //因此它们可用于所有测试在这个描述块
      beforeEach(注(功能(_ $ compile_,_ $ _ rootScope){
        //注射器来自各地的参数名称相匹配时,解开了下划线(_)
        $编译= _ $ compile_;
        $ rootScope = _ $ rootScope_;
      }));  它('替换为相应的内容元素'),功能({
        //编译包含指令HTML的一部分
        VAR元= $编译(&LT;一个伟大眼&GT;&LT; / A-大眼&gt;中)($ rootScope);
        //火灾所有的手表,所以范围前pression {{1 + 1}}将评估
        $ rootScope $摘要()。
        //检查编译元素包含模板化内容
        期待(element.html())toContain(无盖,缭绕火焰,2次);
      });
    });

    调试

    开始在Chrome浏览器测试和调试击按钮。然后打开开发者控制台。

    一些提示:


    • 您可以在您的测试中添加断点。

    • 确保有控制台窗口中没有错误,特别是注射错误。如果你这样做,验证所有您在 karma.config.js 要求(他们将在开发者控制台上市)的js文件正确加载,并包含code你需要(角,模板,指令等)。

    I read many post on internet and SO but couldn't find any solution that works I am trying to write unit test for a directive and want the html files to be served from template cache

    I am using Gulp as a build tool

    The gulp task for test looks like this

    gulp.task('test', function (done) {
        karma.start({
            configFile:__dirname + '/' + config.test.karmaconf,
            singleRun: false
        }, done);
    });
    

    and in karma.conf , I have defined

        browserify: {
            debug: true,
            transform: [['browserify-ng-html2js', {
                module: 'templates',
                extension: 'html'
            }]]
        } 
    

    In unit test , I declared

    beforeEach(angular.mock.module('templates'));
    

    but receiving

    Error: Unexpected request: GET path/to/some.html
    No more request expected
        at $httpBackend 
    

    I also tried to use preprocessors and ngHtml2JsPreprocessor in karma.conf but no success. Could anyone provide solution or point me how can I go about debugging why the templates are not served?

    解决方案

    Solution

    There are multiple ways you could go about doing that. Here's how I do it:

    1. Use gulp-angular-templatecache:

    gulp.task('bundle-common', function() {
      return merge(
        // Store all html files in $templateCache
        gulp.src([
          appDir + '/common/**/*.html'
        ])
        .pipe($$.angularTemplatecache({
          root: 'common'
        }))
    
        // Append everything else: directives, tests, etc.
        gulp.src([
          appDir + '/common/**/*.js'
        ])
      )
      .pipe($$.concat('common.js'))
      .pipe(gulp.dest('public/js/'));
    });
    

    This will output a file named common.js with all your html templates and directives in it.

    It will look somewhat like this:

    angular.module("templates").run(["$templateCache", function($templateCache) {
    $templateCache.put("common/a-great-eye.html","<div>lidless, wreathed in flame, 2 times</div>");}]);
    
    angular.module("common")
    
    .directive('aGreatEye', function () {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: 'common/a-great-eye.html'
        };
    });
    
    ...
    

    1. In karma.conf.js load common.js:

         files: [
          '../vendor/jquery/dist/jquery.js',
          '../vendor/angular/angular.js',
          '../vendor/angular-mocks/angular-mocks.js',
          '../public/js/common.js'
        ]
    

    1. In your test file reference the templates module:

    describe('Unit testing great quotes', function() {
      var $compile,
          $rootScope;
    
      // Load the common module, which contains the directive
      beforeEach(function() {
        module('templates');
        module('common');
      });
    
      // Store references to $rootScope and $compile
      // so they are available to all tests in this describe block
      beforeEach(inject(function(_$compile_, _$rootScope_){
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
      }));
    
      it('Replaces the element with the appropriate content', function() {
        // Compile a piece of HTML containing the directive
        var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
        // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
        $rootScope.$digest();
        // Check that the compiled element contains the templated content
        expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
      });
    });
    

    Debugging

    Start your test in Chrome browser and hit Debug button. Then open Developer Console.

    Few tips:

    • You can add breakpoints in your tests.
    • Make sure that there are no errors in console window, especially injection errors. If you do, verify that all the js files you requested in karma.config.js (they will be listed in Developer Console) are loaded correctly and contain the code you need (angular, templates, directives, etc.).

    这篇关于咕嘟咕嘟角单元测试指令templateUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆