Home AngularJS $window: how can it be beneficial in unit testing? (compared to using window)
Reply: 1

AngularJS $window: how can it be beneficial in unit testing? (compared to using window)

Glenn Mohammad
Glenn Mohammad Published in 2017-12-07 16:47:07Z

While the official docs says, 👇

While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

I still cannot make sense of it. 😕 How can I benefit from $window in my unit tests code? In my snippet below, I can spy/mock and make use of the native window object, with or without $window. How does it cause testability problems?

angular.module('messagePopper', [])
  .factory('popper', function popperFactory($window) {
    return {
      popupMessage(message) {

      popupMessageWith$window(message) {

describe('messagePopper: popper service', () => {
  let $injector;
  let $window;
  let popper;

  beforeEach(() => {

    inject((_$injector_) => {
      $injector = _$injector_;
      $window = $injector.get('$window');
      popper = $injector.get('popper');

  it('should popupMessage correctly', () => {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn(window, 'alert');



  it('should popupMessageWith$window correctly', () => {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn($window, 'alert');



Fiddle here: https://jsfiddle.net/glenn/x42uex66.

Rasmus Hansen
Rasmus Hansen Reply to 2017-12-07 17:05:31Z

While using the global window object works, there might be times where a test will fail, causing the windows object to not be cleaned up for the next test. In which case you would suddenly see a lot of tests failing for seemingly no reason, instead of just the one test that caused the issue.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.328261 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO