Tamil
Tamil

Reputation: 5358

JavaScript Unit Test for custom function

function testRef() {
  if(document.referrer) {
     return /isgoogle/.test(document.referrer)
  }
  return false;
}

Let's assume a function as above. What is a good way to write unit test for such a function [as we can't override document.referrer]. Is there any other good way of testing such scenarios like being inside an iframe, referrer, location, etc., in javascript? I'm currently working with qunit which is quite good. But failed to find a way out in the framework for such scenarios.

Upvotes: 0

Views: 243

Answers (1)

kan
kan

Reputation: 28951

The simplest way is to separate the algorithm from the dependency:

function testRefImpl(doc) {
  if(doc.referrer) {
     return /isgoogle/.test(doc.referrer)
  }
  return false;
}

// unit test
assertFalse(testRefImpl({referer: "abc"}))
assertTrue(testRefImpl({referer: "isgoogle"}))

// dependency declaration module
// so primitive, that there is no point to unit test it.
function testRef() {
  return testRefImpl(document)
}

Upvotes: 2

Related Questions