>有人知道如何覆盖只读对象(如window或[htmlelement].style(中的属性和函数吗?
需要测试的示例函数:
public static getCSSTransitionEvent(element: HTMLElement): string {
let transitions = {
'transition': 'transitionend',
'OTransition': 'oTransitionEnd',
'MozTransition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
};
for (let transition in transitions) {
if (element.style[transition] !== undefined ) {
return transitions[transition];
}
}
return;
}
如何覆盖 element.style 中的过渡属性以测试函数在底部返回未定义?
另一个示例,如何测试此 if 语句
function isCryptoAvailable() {
if (typeof (window.crypto) !== 'undefined' && typeof (window.crypto.getRandomValues) !== 'undefined') {
return true
}
else {
return false
}
}
这是通过属性描述符完成的。只读属性writable
描述符属性设置为 false。只要它们是configurable
的,就可以用Object.defineProperty
重新定义,例如:
const cryptoDescriptor = Object.getOwnPropertyDescriptor(window, 'crypto');
afterEach(() => {
if (origCryptoDescriptor) {
delete window.crypto;
Object.defineProperty(window, 'crypto', cryptoDescriptor);
}
});
it('...', () => {
expect(origCryptoDescriptor).toBeTruthy();
expect(origCryptoDescriptor.configurable).toBeTruthy();
const cryptoMock = ...;
delete window.crypto;
window.crypto = cryptoMock;
...
});
描述符应以afterEach
格式还原,因为即使测试失败,也会执行该描述符。如果属性不可配置,测试将失败。这在某些浏览器中是可能的,因此应从已知失败的浏览器中从套件中排除测试。
这同样涉及涉及非全局函数(如HTMLElement
对象(的函数,但如果可以完全模拟此对象而不是模拟其属性,这是更可取的策略。