【问题标题】:Override read only object within a jasmine unit test覆盖茉莉花单元测试中的只读对象
【发布时间】:2017-03-30 08:03:28
【问题描述】:

有人知道如何覆盖只读对象(如 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 中的 transition 属性以测试函数在底部返回 undefined 吗?

另一个例子,我如何测试这个 if 语句

function isCryptoAvailable() {
    if (typeof (window.crypto) !== 'undefined' && typeof (window.crypto.getRandomValues) !== 'undefined') {
        return true
    }
    else {
        return false
    }
}

【问题讨论】:

    标签: javascript unit-testing typescript jasmine


    【解决方案1】:

    这是通过属性描述符完成的。只读属性将 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 对象)的函数,但如果可以完全模拟此对象而不是模拟其属性,则这是更可取的策略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多