Locate and check script (within webpage) is correct using nightwatchjs

Viewed 80

I'm using nightwatchjs as my testing tool and I need to test that an injected script is correctly displayed on a page, and that the script is correctly populated.

So, the following script html is to be tested (to ensure that it is correctly displayed):

<script type="text/javascript">
    (function() {
        window.dm = window.dm ||{ AjaxData:[]};
        window.dm.AjaxEvent = function(et, d, ssid, ad) {
            dm.AjaxData.push({ et:et, d:d, ssid:ssid, ad:ad});
            window.DotMetricsObj && DotMetricsObj.onAjaxDataUpdate();
        };
        var d = document, h = d.getElementsByTagName('head')[0], s = d.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src='https://uk-script.dotmetrics.net/door.js?id=11373';
        h.appendChild(s);
    } ());
</script>

So firstly, I'd like to test that this script is present on the page, but in a way that is as less brittle as possible. I can test for /html/head/script[13]/text() but this is really brittle and far from ideal.

Is there something in the script itself that I can reference, so the test won't be as brittle?

Secondly, I want to ensure that the script details are correct. This can be a test that will check for the presence of the https://uk-script.dotmetrics.net part of the script for example.

However, I've tried to use my usual css and xpath ways of locating this part of the script but with no luck.

Any help would be appreciated. Thanks.

1 Answers

In line with the paradigm of "assert the what, not the how", the "what" here seems to be making sure that a script got injected into the page. You could use a selector like this one: script[src^="https://uk-script.dotmetrics.net/"], in conjunction with Nightwatch's element function. You could add more selectors to assert the script has the expected attributes like type and async.

In this way, you can skip the implementation detail (the presence of the injecting script) and focus on what I think you really care about (that a script with a correct URL got injected into the page).

Related