yal*_*man 6 html javascript mocking typescript jestjs
我有一个 javascript 函数来检查 html
通过检查元素 ,el是否具有特定大小:
function isOverflow(element: string): boolean {
const el = document.getElementById(element);
return el.scrollHeight > el.clientHeight
}
Run Code Online (Sandbox Code Playgroud)
我想测试一下我的功能。如何设置或模拟scrollHeight和clientHeight?
it('test', () => {
const el = document.createElement("p")
el.setAttribute("id", "overflow")
//How to mock these? This doesn't work "Cannot assign to 'scrollHeight' because it is a read-only property"
el.clientHeight = 2;
el.scrollHeight = 1;
expect(component.isOverflow("overflow")).toBe(true);
})
Run Code Online (Sandbox Code Playgroud)
yal*_*man 12
弄清楚了:
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', { configurable: true, value: 500 })
Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, value: 10 })
Run Code Online (Sandbox Code Playgroud)