Search code examples
javascriptunit-testingjasmine

mock object for document element


I have next test code:

it("Test", function() {
    loadResources();

    expect(document.getElementById('MyElement').innerHTML).toBe("my string");
});

Body of function loadResources():

document.getElementById('MyElement').innerHTML = "my string";

My test fails with following message:

TypeError: Cannot set property "innerHTML" of null.

Looks like I need to create mock object for innerHTML. How I can do this?


Solution

  • I think you should mock getElementById to return a dummy HTMLElement

    JASMINE V1.3 OR BELOW

    var dummyElement = document.createElement('div');
    document.getElementById = jasmine.createSpy('HTML Element').andReturn(dummyElement);
    

    JASMINE V2.0+

    var dummyElement = document.createElement('div');
    document.getElementById = jasmine.createSpy('HTML Element').and.returnValue(dummyElement);
    

    So now, for every call to document.getElementById it will return the dummy element. It will set the dummy element's innerHTML and compare it to the expected result in the end.

    EDIT: And I guess you should replace toBe with toEqual. toBe might fail because it will test for object identity instead of value equality.

    EDIT2 (regarding multiple ID): I am not sure, but you could call a fake instead. It will create a new HTML element for each ID (if it doesn't exist yet) and store it in an object literal for future use (i.e. other calls to getElementById with same ID)

    JASMINE V1.3 OR BELOW

    var HTMLElements = {};
    document.getElementById = jasmine.createSpy('HTML Element').andCallFake(function(ID) {
       if(!HTMLElements[ID]) {
          var newElement = document.createElement('div');
          HTMLElements[ID] = newElement;
       }
       return HTMLElements[ID];
    });
    

    JASMINE V2.0+

    var HTMLElements = {};
    document.getElementById = jasmine.createSpy('HTML Element').and.callFake(function(ID) {
       if(!HTMLElements[ID]) {
          var newElement = document.createElement('div');
          HTMLElements[ID] = newElement;
       }
       return HTMLElements[ID];
    });