Your script is working fine, just because you can’t see it doesn’t mean that it isn’t there.
var head = document.getElementsByTagName('head');
var canonical = document.createElement('link');
Surely your easiest workaround is to just use the canonical link in the way it was intended.
<link rel="canonical" href="testURL" />