如何在templateCache中测试模板的存在?

时间:2015-06-08 07:16:43

标签: angularjs unit-testing karma-jasmine

在我的JS中,我有以下代码部分:

var $raw_html = $templateCache.get(attr.sidePopupUrl);                
    if ($raw_html) {  // if the template exist in the cache, then continue with the popupElement function
            popupElement($raw_html);
    }else{ // if template not exist, fetch the template using $http and put the respond into template cache, then continue with the popupElement function

         $http.get(attr.sidePopupUrl).then(function(response) {
             var $raw_html = response.data;
             $templateCache.put(attr.sidePopupUrl, $raw_html);
             popupElement($raw_html);
         });

    }

在我的测试中,我希望测试是这样的,但不知道如何编写它:

describe('Popup template', function(){
        it("Should continue with the popupElement function if template exist in templateCache", function(){
                 // Anyone have ideas?
        });

});

describe('Popup template', function(){
        it("Should fetch from the server and put the retrieved response to the template cache if the template is not available in the cache, then continue the popupElement function", function(){
                // Anyone have ideas?
        });

});

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

You can inject the $templateCache into your tests and test the existence of a template like this:

describe('The popup template', function() {

    var $templateCache;
    beforeEach(inject(function($injector) {
        $templateCache = $injector.get('$templateCache');
    });

    it('should use a template that exists', function() {
        // If you are using something such as chai
        expect($templateCache.get('your/template/url.html')).to.be.ok;

        // If you aren't use an assertion library
        if (!$templateCache.get('your/template/url.html')) {
            throw new Error('Template does not exist');
        }
    });
});