我怎样才能在放肆的无头浏览器中使用templateUrl测试指令 [英] How can I test a directive using templateUrl in Chutzpah's headless browser

查看:296
本文介绍了我怎样才能在放肆的无头浏览器中使用templateUrl测试指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何让喜欢放肆的Visual Studio的测试适配器一具无头的浏览器,允许指令访问它的html的模板文件?放肆使用PhantomJS对于这似乎限制了我的选择模拟浏览器。

我用放肆测试适配器2.5和1.2.0 AngularJS - R.2。

我得到的错误:


  

意外的请求:GET对myApp /指令/ template.html


这是由角试图使用$ HTTP服务来访问我的指令的模板引起的。

我已经发现了一些不同的解决方法:


  1. 使用手动XMLHtt prequest导入模板。

  2. 使用像咕噜一个实用程序来内联模板到你的指令的JS code。

  3. $ httpBackend.when('GET','对myApp /指令/ template.html')直通() - 在端到端测试,而不是单元测试这只作品

  4. 直接把模板放到测试code。

这些选项无特别满足我。我想preFER才能够让指令载入它的透明模板,这样我就可以测试它作为一个组件。有没有一种方法,我可以得到这个场景的工作?

举例code:

  angular.module('myDirective',[])。指令(myDirective',函数(){
    返回{
        限制:'E',
        transclude:真实,
        templateUrl:对myApp /指令/ template.html',
        //一些其他选择,为简洁起见省略。
    };
});

template.html:

 < D​​IV>< D​​IV NG-transclude>< / DIV>< / DIV>

例如茉莉花测试:

 描述('myDirective',函数(){
    //分配$使用注入()范围,加载模块等。
    //插入解决方法$ httpBackend这里我装templateUrl。
    它('应该transclude内容',函数(){
        VAR元= $编译(<我的指导性>看看妈妈,我在我的指导下和;!/我的指导性>中)($范围内);
        $ $范围摘要()。        期待(element.text()修剪()。)TOBE(看妈妈,我在我的指令!)。
    });
}


解决方案

我设法得到它的工作,用放肆的编译选项。我移植<一个href=\"https://github.com/karma-runner/karma-ng-html2js-$p$pprocessor\">karma-ng-html2js-$p$pprocessor到PowerShell脚本,然后调用从放肆编译HTML到JS文件。

旁边chutzpah.json设置文件添加PowerShell脚本(下面的脚本包含pre preND preFIX和StripSuffix未经测试的支持)

  https://github.com/karma-runner/karma-ng-html2js-$p$pprocessor排名PowerShell的端口参数(
    [参数(强制性= $真实)] [字符串] $路径,
    [字符串] $模块='',
    [字符串] $地带preFIX ='',
    [字符串] $prePEND preFIX ='',
    [字符串] $ StripSuffix =''
)功能EscapeContent($内容){
    $内容-replace\\\\,\\\\\\\\-replace',\\'-replace'R''N,\\ N'+'N'
}功能重命名($文件名){
    $prePEND preFIX+($文件名-replace$地带preFIX,''-replace$ StripSuffix,''-replace\\\\,/)
}$模板= IF($模块-eq){
    angular.module({0},[])。运行(功能(`$ templateCache){{`N`
      +`$ templateCache.put('{0}','N'{2}');`N`
      +}});`N
  }其他{
    (功能(模块){{`N`
        +尝试{{`N`
        +模块= angular.module({1}');`N`
        +}}赶上(E){{`N`
        +模块= angular.module({1},[]);`N`
        +}}`N`
        +module.run(功能(`$ templateCache){{`N`
        +`$ templateCache.put('{0}','N'{2}');`N`
        +}});`N`
        +}})();'N
  }GET-ChildItem $路径-Recurse -Filter *。html的|的foreach对象{
    $内容=获取内容$ _全名。|输出字符串
    $内容= EscapeContent $内容
    $文件名=重命名$($ _。全名)
    ($模板-f$文件名,$模块,$内容)|设置内容$($ _。全名)的.js
}

新增的编译配置chutzpah.json和编译JS文件添加到引用(参考可以从测试文件中添加的,但我preFER使用chutzpah.json管理所有的引用)

  {
    参考:
        {路径:./path/to/templates/,包含:* .html.js},
    ]
    编译:{
        扩展:[名.html],
        ExtensionsWithNoOutput:.html.js],
        SourceDirectory:./path/to/templates,
        OutDirectory:./path/to/templates,
        可执行文件:%powershellexe%,
        论据:?-NoProfile%chutzpahsettingsdir%\\\\放肆-NG-html2js-compiler.ps1 -Path'/路径/要/模板/ - 模块'模板'-strip preFIX'+(= \\ \\\\\\模板)'
    }
}

在您的测试文件,加载模块,在我的情况下,他们都在模版模块

  beforeEach(模块('模板'));
//或交替
beforeEach(模块('/路径/要/模板/ foo.html'));

Does anyone know how to get a headless browser like Chutzpah's Visual Studio Test Adapter to allow a directive to access its .html template file? Chutzpah uses PhantomJS for a headless browser which appears to limit my options.

I'm using Chutzpah Test Adapter 2.5 and AngularJS 1.2.0-r.2.

I get the error:

Unexpected request: GET myApp/directives/template.html

Which is caused by Angular attempting to use the $http service to access my directive's template.

I've found a few different workarounds:

  1. Manually using XMLHttpRequest to import the templates.
  2. Using a utility like Grunt to inline the template into your directive's JS code.
  3. $httpBackend.when('GET', 'myApp/directives/template.html').passThrough() - this only works in e2e tests, not unit tests.
  4. Put the template directly into the test code.

None of these options particularly satisfy me. I'd prefer to be able to let the directive load its template transparently so I can test it as a component. Is there a way I can get this scenario working?

Example code:

angular.module('myDirective', []).directive('myDirective', function() {
    return {
        restrict: 'E',
        transclude: true,
        templateUrl: 'myApp/directives/template.html',
        // Some other options, omitted for brevity.
    };
});

template.html:

<div><div ng-transclude></div></div>

Example Jasmine test:

describe('myDirective', function() {
    // Assign $scope using inject(), load module etc.
    // Insert workaround for $httpBackend loading my templateUrl here.
    it('should transclude content', function() {
        var element = $compile("<my-directive>Look Mom, I'm in my directive!</my-directive>")($scope);
        $scope.$digest();

        expect(element.text().trim()).toBe("Look Mom, I'm in my directive!");
    });
}

解决方案

I managed to get it working, using Chutzpah's compile option. I ported karma-ng-html2js-preprocessor into a PowerShell script and then call that from Chutzpah to compile the HTML into JS files.

Added PowerShell script next to chutzpah.json settings file (the below script contains untested support for PreprendPrefix and StripSuffix)

# PowerShell port of https://github.com/karma-runner/karma-ng-html2js-preprocessor

Param (
    [parameter(Mandatory=$true)] [string] $Path,
    [string] $Module = '',
    [string] $StripPrefix = '',
    [string] $PrependPrefix = '',
    [string] $StripSuffix = ''
)

Function EscapeContent($content) {
    $content -replace "\\", "\\\\" -replace "'", "\'" -replace  "`r?`n", "\n' +`n    '"
}

Function Rename($fileName) {
    "$PrependPrefix" + ("$fileName" -replace "$StripPrefix", '' -replace "$StripSuffix", '' -replace "\\", "/")
}

$Template = If ("$Module" -eq "") {
    "angular.module('{0}', []).run(function(`$templateCache) {{`n" `
      + "  `$templateCache.put('{0}',`n    '{2}');`n" `
      + "}});`n"
  } Else {
    "(function(module) {{`n" `
        + "try {{`n" `
        + "  module = angular.module('{1}');`n" `
        + "}} catch (e) {{`n" `
        + "  module = angular.module('{1}', []);`n" `
        + "}}`n" `
        + "module.run(function(`$templateCache) {{`n" `
        + "  `$templateCache.put('{0}',`n    '{2}');`n" `
        + "}});`n" `
        + "}})();`n"
  }

Get-ChildItem $Path -Recurse -Filter *.html | Foreach-Object {
    $content = Get-Content $_.FullName | Out-String
    $content = EscapeContent $content
    $fileName = Rename "$($_.FullName)"
    ("$Template" -f "$fileName", "$Module", "$content") | Set-Content "$($_.FullName).js"
}

Added compile configuration to chutzpah.json and add the "compiled" JS files to References (the reference could added from the test file, but I prefer to use chutzpah.json to manage all the references)

{
    "References": [
        { "Path": "./path/to/templates/", "Include": "*.html.js" },
    ],
    "Compile": {
        "Extensions": [".html"],
        "ExtensionsWithNoOutput": [".html.js"],
        "SourceDirectory": "./path/to/templates",
        "OutDirectory": "./path/to/templates",
        "Executable": "%powershellexe%",
        "Arguments": "-NoProfile %chutzpahsettingsdir%\\chutzpah-ng-html2js-compiler.ps1 -Path '/path/to/templates/' -Module 'templates' -StripPrefix '.+(?=\\\\templates)'"
    }
}

In your test files, load the module, in my case they are all in 'templates' module

beforeEach(module('templates'));
// or alternatively
beforeEach(module('/path/to/templates/foo.html'));

这篇关于我怎样才能在放肆的无头浏览器中使用templateUrl测试指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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