有谁知道如何覆盖只读对象(如窗口或 [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。只要它们是可配置的
,就可以使用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
对象,但如果可以完全模拟此对象而不是模拟其属性,则这是更可取的策略。
关于javascript - 覆盖 Jasmine 单元测试中的只读对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43111905/