2

I have a JavaScript function with "document.write" in it, as below:

function sampleFunction(){  
document.write('hello world');  
}

And, for this wrote a unit test case in Jasmine, as below:

describe("testing function", function() {    
  it("should give output", function() {     
      expect(sampleFunction()).toBe('hello world');  
      expect(sampleFunction()).toContain('hello');   
  });  
    });

But when we run it using Karma, it opens up a web page just print 'hello world' on it and test case fails.

Can you please suggest what is the correct way to write unit test case for this function

Many Thanks!

Mandeep Rehal
  • 93
  • 2
  • 4
  • 11

1 Answers1

2

Unit tests are generally best used for testing small, digestible, and purely functional pieces of code. It is much harder to use unit testing on things that have an internal state like a counter that increments each time something is called or that need to access external IO like writing to the document, which is your situation.

For testing whether the document has been updated accurately you might want to consider implementing what many engineers have begun to call "end-to-end" testing. This is a decent medium article that provides a little more insight, although it's not really an authoritative source.

Karma, as you may have picked up on already, is one tool that allows you to run end-to-end testing in one or more browsers. You are expecting sampleFunction to return a value, but what you should be doing is testing that the document's content is now "hello world" instead of whatever it was before. Here's a decent, albeit outdated, article explaining how to do that.

Peter Van Drunen
  • 543
  • 5
  • 15