Question

I'm trying to write an end-to-end test of my AngularJS app where I check that when a certain parameter is in the URL, something happens. However, $routeParams is an empty object. This guy had the same problem. I'm trying to determine that some text appears in the UI when ?code=whatever is in the URL. My app works, and this route does what's intended:

$routeProvider.when '/',
  resolve:
    redirect: ($location, $routeParams, $http, $cookieStore) ->
      console.log $routeParams
      code = $routeParams.code
      console.log 'code: ' + code
      if code
        // do something
      else
        // do something else

When I visit test-index.html?code=123 via the Karma test runner, in the browser console I see:

Object {}
code: undefined

I would expect to have to mock out $routeParams in a unit test, but I assumed an end-to-end test would function like the real app. Why is $routeParams completely empty in my test when there is definitely a URL parameter?

Edit: here is my test:

it 'fills in the input field when code is in URL', ->
  browser().navigateTo '/base/test-index.html?code=123#/'
  element('a.some-link').click()
  expect(input('my_param.value').val()).toBe 'something that gets set when code in URL'
Was it helpful?

Solution

$route, $routeParams and most functions of $location are working on the part of url after "#". So, as in your example "/base/test-index.html?code=123#/", angular only sees "/" after "#", nothing else, that's why you got empty $routeParams. Also, you shouldn't use $routeParams in resolve function, use $route.current.params instead.

Try to change

browser().navigateTo '/base/test-index.html?code=123#/'

to

browser().navigateTo '/base/test-index.html#/?code=123'

And in your redirect

console.log $route.current.params

OTHER TIPS

This feels janky as hell, because I'm altering the actual to suit the test because AngularJS isn't filling out $routeParams like it should. Thanks to this generic JavaScript solution, I added QueryString to another JS file and included it in both my app index.html as well as test-index.html. Then, in my routes.js, I do code = $routeParams.code || QueryString.code. So if $routeParams is blank, which only seems to happen in a test, then the ?code=blah parameter value is gotten via good ol' JavaScript window.location parsing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top