简体   繁体   中英

How Do i change a url in a javascript file using javascript Automation Testing

I am trying to modify a URL within a javascript file in my automation tests. This is so I can point off to a stubbed version of a service. The framework i am using for testing is Serenity-js (Using protractor)

In my HTML DOM I have:

<script type="text/javascript" src="main.js"></script>

main.js

var DataService = (function () {
    function DataService(http) {
        this.http = http;
    }
    DataService.prototype.getStudentDetails = function (id) {
        var parcel = this.http
            .get('http://127.0.0.1/endpoint/' + id)
            .map(function (res) {
            return __WEBPACK_IMPORTED_MODULE_2__student_model__["a"].createStudent(res.json());
        });
        return student;
    };
    return DataService;
}());

The part i need to change is 127.0.0.1/endpoint

I know I cold change the HTML DOM using $.document.write or $().append but don't know how to change/overwirte a DOM element.

This is quite simple, but there are so many ways of doing it!

  1. As part of the setup phase before running your tests, you could just pre-process the main.js file using a sed or awk script and replace all occurrences of the 127... string with something else.
  2. Change the code in the production system to read from a configuration variable containing all the url endpoints. You could then just change that object in your test script.
  3. Use your test script to replace the function with something else. This is what @alok suggests in the comments, but the comment was missing prototype , and the method should also not have been invoked, so the code should look something like this:

Example of #3:

 const newFnString = DataService.prototype.getStudentDetails.toString()
                         .replace("127.0.0.1", "something.com");
 DataService.prototype.getStudentDetails = new Function(newFnString);

Of course, you could just have replaced DataService.prototype.getStudentDetails with any given function, as you have total control over it (unless it is hidden in a closure).

PS Trying to secure your systems by making it harder to tamper with the javascript is just security through obscurity - it's not real. Any attacker can just read the network requests anyhow, and replay them in curl or Postman.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM