Modify an http response in a protractor test

2019-02-10 16:53发布

I'm trying to write some end to end tests for our application's login process, but am having trouble getting my head around the best way to set up the scenario where the user needs to change his password.

When our server responds to a successful login, a user object is returned with a changePassword field. The client then inspects the response and redirects accordingly.

My problem is getting the test set up so that the changePassword field is set - what is the best approach to use?

I see my options as:

  1. Have a test set up and tear-down script for the server that creates a brand new user specifically for the test run with changePassword flag set in the database.

    This seems like the most end to end approach, but is probably also the most effort & code.

  2. Somehow intercept the http response in the test and modify the changePassword flag to be set for this test only.

  3. Mock the http response completely. Using this approach is the most removed from an end to end test, but is perhaps the simplest?

Which is the best or most common approach? Also any general pointers on how to actually implement the above (particularly 1 and 2) with protractor would be great - I'm finding it hard to conceptually get straight in my head, and hence hard to know what to search for.

I'm using protractor as the test framework, with angular.js powering the client side, and a node server running utilising (among other things) express.js and mongoDB.

2条回答
小情绪 Triste *
2楼-- · 2019-02-10 17:37

I think your first approach is the most appropriate.

It would be useful anyway to test the new user creation, so it is not a waste. And for example this example seems to be something similar: http://product.moveline.com/testing-angular-apps-end-to-end-with-protractor.html

查看更多
The star\"
3楼-- · 2019-02-10 17:50

Having thought about this further, option 1 is the best solution, but is not always possible.

Option 2 is also possible, and option 3 should be avoided.

For option two, a mock module can be created like so: (coffeescript)

e2eInterceptors =->

  angular.module('e2eInterceptors', [])
  .factory('loginInterceptor', ()->
    response: (response)->
      # Only edit responses we are interested in
      return response unless response.match(/login/)
      # do the modifiations
      response.data.changePassword = true
      # return the response
      return response
  )
  .config(($httpProvider)->
    $httpProvider.interceptors.push('loginInterceptor')
  )

You can then inject this module into your tests using

browser.addMockModule('e2eInterceptors', e2eInterceptors)

If you want to do this globally, you can put this in the onPrepare function in your protractor file, otherwise just call it when needed in tests.

查看更多
登录 后发表回答