文档元素的模拟对象 [英] mock object for document element

查看:98
本文介绍了文档元素的模拟对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个测试代码:

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

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

功能体 loadResources()

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

我的测试失败,并显示以下消息:

My test fails with following message:


TypeError:无法设置属性innerHTML null。

TypeError: Cannot set property "innerHTML" of null.

看起来我需要为innerHTML创建模拟对象。我怎么做?

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

推荐答案

我认为你应该模拟 getElementById 返回虚拟HTMLElement

I think you should mock getElementById to return a dummy HTMLElement

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

现在,每次调用 document.getElementById 它将返回虚拟元素。它将设置虚拟元素的innerHTML并将其与预期结果进行比较。

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.

编辑:我想你应该替换 toBe toEqual toBe 可能会失败,因为它将测试对象标识而不是值相等。

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

EDIT2(关于多个ID):我不确定,但你可以打电话给假的。它将为每个ID创建一个新的HTML元素(如果它还不存在)并将其存储在对象文字中以供将来使用(即,对其它的其他调用 getElementById ID)

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)

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];
});

这篇关于文档元素的模拟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆