cppcho cppcho - 1 year ago 131
Node.js Question

Mocha complains Reference Error: URL is not defined

Sorry I don't know if this is a stupid question or not but I cannot find the answer.

I have a pure function in javascript which check if the argument is a correct URL

isValidUrl(url) {
const protocol = new URL(url).protocol;

The code runs fine in browser. But I would like to write a test using mocha for it. And mocha complains "ReferenceError: URL is not defined". So does that mean server side JS does not have URL class? Do I need to use something like headless browser to test it?

Thanks a lot.

Answer Source

Node and friends, where your tests are likely running, implement the ECMAScript (JS) spec. The URL class is from this WhatWG spec. The JS spec does not have any reference to a URL class, which explains your immediate problem.

Node also implements its own CommonJS-based modules, one of which is a URL module. It doesn't appear to have the same interface, however.

Using Mocha with Karma to run tests in a headless browser, like PhantomJS, is probably a better solution. You'll get an accurate, if slightly out of date, version of chromium to test within. You can also set Karma up to use other browsers, if they are available on the test machine.