RSSAmplifier

Damian Nicholson · Jul 21, 2015

Stubbing AngularJS $window

0
Sign in to vote or save

Damian Nicholson · Damian Nicholson

Weathered white building with red "Bingo Bongo Group" sign, wooden-framed window with metal grate, and climbing vines.

It’s sometimes useful to be able to perform a page redirect using AngularJS low-level $window API.

What’s not ideal is when this behaviour needs testing and the sucker actually performs a redirect half way through your suite leaving you in limbo – not cool!

This is where AngularJS liberal use of Dependency Injection(DI) really helps as we can utilise its inbuilt $provide service to stub out $window and overcome the issue.

Below is an example of how I achieved this in Jasmine / CoffeeScript:

ctrl = scope = $window = null
beforeEach ->
  module 'my_module', ($provide) ->
    $provide.constant '$window', { location: { href: "dummy" } }
  inject ($rootScope, $controller, _$window_) ->
    scope = $rootScope.$new()
    $window = _$window_
    ctrl  = $controller 'MyController', $scope: scope
it "should redirect to '/some-other-url'", ->
  expect($window.location.href).toEqual("dummy")
  scope.myMethodWhichRedirects()
  expect($window.location.href).toEqual("some-other-url")

Read the original on damiannicholson.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.