【问题标题】:How can I do a unit test to see if angular is undefined?如何进行单元测试以查看角度是否未定义?
【发布时间】:2016-07-21 02:08:57
【问题描述】:

我在单元测试中使用 angular 版本 1 和 jasmine。

我想做的测试是:

例如,当我在 ie7 中加载 index.html 页面时,我加载了一个 html 横幅,上面写着下载最新的浏览器。

我目前正在索引页面上使用 JQuery 加载一个 html 模板。

是否可以测试它,因为它在 Angular 应用程序之外。

这是我在 index.html 页面上的当前代码:

<!doctype html>
    <head>       
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>      

        <base href="/app/" />

         <!-- Is Angular supported -->  
        <script>
            if(window.angular === undefined)              
                 $(function(){$("#angularNotSupportedModal").load("/app/noAngularModal.html");});
        </script>   

    </head>
    <body ng-app="app" ng-cloak> 
        <div id="angularNotSupportedModal"></div>      

        <div ui-view></div>

        <!-- Application -->
        <script src="/scripts/app.js"></script>

        <!-- Config -->
        <script src="/scripts/config.js"></script>
    </body>
</html>

任何建议都会很棒。

谢谢

【问题讨论】:

    标签: javascript jquery angularjs unit-testing jasmine


    【解决方案1】:

    任务缩小到旧的 jQuery 测试,这很乏味但可能。 jQuery 是否可以被监视或应该完全被存根和模拟,这取决于代码。

    被测试的脚本应该被隔离到单独的函数中才能正确测试。可能是这样的:

    it('should call through $ chain', (done) => {
      var angular = window.angular;
      window.angular = undefined;
    
      spyOn(jQuery.prototype, 'ready').and.callThrough();
      spyOn(jQuery.prototype, 'load').and.callThrough();
    
      // make spy not break the chain
      var init = jQuery.prototype.init.bind(jQuery.prototype);
      spyOn(jQuery.prototype, 'init').and.callFake(init);
    
      window.runAngularNotSupportedFunction();
    
      expect(jQuery.prototype.ready).toHaveBeenCalledWith(jasmine.any(Function));
      expect(jQuery.prototype.init).toHaveBeenCalledWith('#angularNotSupportedModal', undefined);
      expect(jQuery.prototype.load).toHaveBeenCalledWith('/app/noAngularModal.html');
    
      window.angular = angular;
      jQuery.ready.promise().done(done)
    })
    

    【讨论】:

    • 这就是测试jQuery代码的方法。你还没有具体说明你做了什么以及为什么它不起作用。
    • 找不到你使用的jQuery变量,我应该注入它吗?
    • 如果是这样,我该怎么做?
    • 是的,你应该在测试中加载 jQuery 和 Angular。
    • 这是我在运行测试时遇到的 git bash 错误:PhantomJS 1.9.8 (Windows 7 0.0.0) Is Angular Supported Tests should call through jquery chain FAILED TypeError: 'undefined' is not一个对象(评估'jQuery.prototype')
    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2019-05-15
    • 2020-07-10
    相关资源
    最近更新 更多