加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – 单位测试$sce.trustAsHtml的输出

发布时间:2020-12-17 08:08:02 所属栏目:安全 来源:网络整理
导读:我在Angular写一个REST应用程序,我想为它编写单元测试(当然!)。我有一个控制器,从json的REST服务中获取博客帖子列表,并将摘要放入$ scope中,因此我可以在视图中显示它们。 起初,博客文章刚刚显示为文本,即 p博客正文 / p,而不是渲染为解析的HTML,直
我在Angular写一个REST应用程序,我想为它编写单元测试(当然!)。我有一个控制器,从json的REST服务中获取博客帖子列表,并将摘要放入$ scope中,因此我可以在视图中显示它们。

起初,博客文章刚刚显示为文本,即< p>博客正文< / p>,而不是渲染为解析的HTML,直到我发现您可以使用ng-bind-html与$sce service结合使用。正确显示博文。

单元测试时出现问题。我试图用一些HTML模拟一个json响应,然后测试我的控制器正确处理HTML。这是我的代码:

调节器

.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": "u003Cpu003EPost body.u003C/pu003En","summary": "u003Cpu003ESummary.u003C/pu003En"
                    },"created": "1388415860"
                }
            ]};
        var processedResponse = [{
                "body": {
                    "value": "u003Cpu003EPost body.u003C/pu003En","summary": "u003Cpu003ESummary.u003C/pu003En"
                },"created": "1388415860000",previewText: $sce.trustAsHtml("u003Cpu003ESummary.u003C/pu003En")
        }];

        $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);
    });
});

当我通过Karma测试赛跑者运行上述时,我得到以下回应:

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>
    ',previewText : { $$unwrapTrustedValue : Function } }     ].

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

我的问题是,首先我正是以正确的方式来解决这个问题?

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

由于迈克尔 – 罗克利给出的答案对我来说并不奏效,我想指出另一个解决方案。在我的例子中,我使用一个过滤器,它将每个字符串的出现包装在另一个字符串中,并具有一个类别为“highlight”的跨度。换句话说,我要让字被突出显示。这是代码:
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函数来使我的测试工作:

it('01: should add a span with class 'highlight' around each mathing string.',inject(function ($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>.'); 
}));

更新:

正如@gugol所指出的那样,最好不要使用像$ unwrapTrustedValue这样的Angular内部方法。更好的方法是在$ sce服务上使用public getTrustedHtml方法。像这样:

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($sce.getTrustedHtml(result)).toEqual('this <span class="highlighted">str</span> contains a <span class="highlighted">str</span> that will be a highlighted <span class="highlighted">str</span>.');
}));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读