mock object for document element

前端 未结 3 789
长情又很酷
长情又很酷 2020-12-23 11:22

I have next test code:

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

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


        
相关标签:
3条回答
  • 2020-12-23 11:56

    Try this:

    it('should blah', () => {
      const elementMock = {
        innerHTML: 'my string'
      };    
    
      loadResources();
    
      jasmine.spyOn(document, 'getElementById').and.returnValue(elementMock);
    
      expect(document.getElementById('MyElement').innerHTML).toBe('my string');
    });
    
    0 讨论(0)
  • 2020-12-23 11:59

    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];
    });
    
    0 讨论(0)
  • 2020-12-23 12:09

    Set up a document body and getElement by id. I'm using jest and this works fine. Check out this example from jest documentation.

    test('Toggle innerHtml of an element', () =>{
    document.body.innerHTML =
                '<div>' +
                '  <div id="username" >Hello</div>' +
                '  <button id="button" />' +
                '</div>';
    var el = document.getElementById('username');
    var newText = 'new inner text';
    el.innerText = newText;
    expect(el.innerText).toEqual(newText);
    });
    
    0 讨论(0)
提交回复
热议问题