单元测试$ sce.trustAsHtml的输出角 [英] Unit testing the output of $sce.trustAsHtml in Angular

查看:337
本文介绍了单元测试$ sce.trustAsHtml的输出角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在角一个REST的应用程序,我想编写单元测试它(当然!)。我有一个控制器,它获取博客文章的列表,REST服务以JSON并把总结到$范围,这样我就可以在视图中显示出来。

I am writing a REST app in Angular and I want to write unit tests for it (of course!). I have a controller which gets a list of blog posts from a REST service in json and puts the summaries into the $scope, so I can display them in the view.

起初博客文章只是显示为文本即< P>博客身体LT; / P> ,而不是渲染为解析的HTML,直到我发现你//文档:可以与的 NG绑定-HTML 。 angularjs.org/api/ng.%24sce\">$sce服务。这在现在正确显示的博客文章方面工作正常。

At first the blog posts were just displaying as text ie <p>Blog body</p>, rather than rendering as parsed HTML, until I discovered that you can use ng-bind-html in conjunction with the $sce service. This now works fine in terms of displaying the blog posts correctly.

在出现问题时,单元测试。我试图嘲弄与一些HTML的JSON响应,然后测试,我的控制器正确处理与HTML。这里是我的code:

The problem arises when unit testing. I am trying to mock a json response with some HTML and then test that my controller is correctly dealing with the HTML. Here is my code:

.controller( 'HomeCtrl', function HomeController( $scope, $http, $sce ) {
    $scope.posts = {};
    $http.get('../drupal/node.json').success(function (data) {
        var posts;
        posts = data.list;

        for(var i = 0; i < posts.length; i ++) {
            posts[i].previewText = $sce.trustAsHtml(posts[i].body.summary);
            posts[i].created = posts[i].created + '000'; // add milliseconds so it can be properly formatted 
        }
        $scope.posts = posts;
    });
})

单元测试

describe('HomeCtrl', function() {
    var $httpBackend, $rootScope, $sce, createController;

    beforeEach(inject(function ($injector) {
        // Set up the mock http service responses
        $httpBackend = $injector.get('$httpBackend');

        // Get hold of a scope (i.e. the root scope)
        $rootScope = $injector.get('$rootScope');
        // The $controller service is used to create instances of controllers
        var $controller = $injector.get('$controller');

        $sce = $injector.get('$sce');

        createController = function() {
            return $controller('HomeCtrl', {
                '$scope': $rootScope
            });
        };
    }));

    it('should get a list of blog posts', function() {
        var rawResponse = {
            "list": [
                {
                    "body": {
                        "value": "\u003Cp\u003EPost body.\u003C\/p\u003E\n",
                        "summary": "\u003Cp\u003ESummary.\u003C\/p\u003E\n"
                    },
                    "created": "1388415860"
                }
            ]};
        var processedResponse = [{
                "body": {
                    "value": "\u003Cp\u003EPost body.\u003C\/p\u003E\n",
                    "summary": "\u003Cp\u003ESummary.\u003C\/p\u003E\n"
                },
                "created": "1388415860000",
            previewText: $sce.trustAsHtml("\u003Cp\u003ESummary.\u003C\/p\u003E\n")
        }];

        $httpBackend.when('GET', '../drupal/node.json').respond(rawResponse);
        $httpBackend.expectGET("../drupal/node.json").respond(rawResponse);
        var homeCtrl = createController();
        expect(homeCtrl).toBeTruthy();
        $httpBackend.flush();
        expect($rootScope.posts).toEqual(processedResponse);
    });
});

当我通过噶测试运行运行上面的,我得到以下回应:

When I run the above through the Karma test runner, I get the following response:

Chrome 31.0.1650 (Windows) home section HomeCtrl should get a list of blog posts FAILED
    Expected [ { body : { value : '<p>Post body.</p>
    ', summary : '<p>Summary.</p>
    ' }, created : '1388415860000', previewText : { $$unwrapTrustedValue : Function } }          ] to equal [ { body
: { value : '<p>Post body.</p>
    ', summary : '<p>Summary.</p>
    ' }, created : '1388415860000', previewText : { $$unwrapTrustedValue : Function } }     ].

我怀疑问题是由于一个事实,即 $ sce.trustAsHtml 返回一个包含一个函数,而不是字符串的对象。

I suspect the problem is due to the fact that $sce.trustAsHtml returns an object containing a function, rather than a string.

我的问题是,第一,我在正确的方式处理这个问题?

其次,如果是这样,我应该怎么去测试 $ sce.trustAsHtml 的输出?

Secondly, if so, how should I go about testing the output of $sce.trustAsHtml?

推荐答案

由于迈克尔 - 布罗姆利给出的答案并没有为我工作,我想指出的另一种解决方案。在我来说,我使用的是过滤器,包装了一个字符串的每次出现在另一个字符串中使用具有类亮点的跨度。换句话说,我要加以强调的话。这里是code:

Since the answer given by michael-bromley didn't work for me I want to point out another solution. In my case I was using a filter that wraps each occurrence of a string in another string with a span that has a class of 'highlight'. In other words, I want words to be highlighted. Here is the code:

angular.module('myModule').filter('highlight', function ($sce) {
    return function (input, str) {
        return $sce.trustAsHtml((input || '').replace(new RegExp(str, 'gi'), '<span class=\"highlighted\">$&</span>'));
    };
});

我用的是$ SCE服务信任所产生的价值为HTML。为了验证这一点,我需要使用$$ unwrapTrustedValue功能上所产生的价值,让我的测试工作:

I use the $sce service to trust the resulting value as HTML. To test this I need to use the $$unwrapTrustedValue function on the resulting value to get my test working:

it('01: should add a span with class \'highlight\' around each mathing string.', inject(function ($sce, $filter) {
    // Execute
    var result = $filter('highlight')('this str contains a str that will be a highlighted str.', 'str');

    // Test
    expect(result.$$unwrapTrustedValue()).toEqual('this <span class="highlighted">str</span> contains a <span class="highlighted">str</span> that will be a highlighted <span class="highlighted">str</span>.'); 
}));

这篇关于单元测试$ sce.trustAsHtml的输出角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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