0

How could I test that this function does what it is supposed to do? I am working with Jasmine as Testing framework.

function () { //if IE, return version number
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    var trident = ua.indexOf('Trident/');

    if (msie > 0) { // IE 10 or older
      return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    if (trident > 0) { // IE 11 (or newer)
      var rv = ua.indexOf('rv:');
      return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    // other browser
    return false;
  }

I don't mind if this function works or not. I need to write a test for it. This means it doesn't help me if you tell me it works.

1 Answer 1

1

You need to mock window.navigator.userAgent in some way. The most simple solution is to introduce a wrapper:

function () { //if IE, return version number
    var ua = window.navigator.userAgent;
    return realFunction(ua);
}

and then write tests for realFunction where you pass values which you can get from a number of browsers by executing window.navigator.userAgent in their JavaScript console.

You can also try to assign a value to window.navigator.userAgent and then call the original function but I'm not 100% sure how different browsers respond to such manipulation (they might ignore assignments of this kind or throw errors). That's why I think the wrapper function approach is cleaner and safer.

The other option is something like Selenium which can start a web browser from a test and control it remotely (opening pages, running JavaScript).

But this approach is brittle (especially when it comes to IE) and slow and complex to set up (when you want to test more than a single version of any browser).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.