How can I do a unit test to see if angular is unde

2019-01-20 04:59发布

问题:

I'm using angular version 1 with jasmine for my unit tests.

The test I want to do is:

When I load the index.html page in ie7 for example I load in a html banner saying download latest browser.

I'm currently loading a html template using JQuery on the index page.

Is it possible to test this since its outside the angular app.

This is my current code on my index.html page:

<!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>

Any suggestions would be great.

Thanks

回答1:

The task narrows down to good old jQuery testing, which is tedious but possible. It depends on the code if jQuery can be just spied or should be totally stubbed and mocked.

The tested script should be isolated to separate function to be tested properly. It may be something like this:

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