【问题标题】:Unit test: mock document used by an imported TypeScript dependency?单元测试:导入的 TypeScript 依赖项使用的模拟文档?
【发布时间】:2017-04-27 12:29:35
【问题描述】:

我需要以某种方式模拟 document 对象,以便能够对遗留的 TypeScript 类进行单元测试。该类导入另一个类 (View.ts),该类具有一个 3-rd 方模块的 import,而该类又导入了其他假设 document 存在的东西。

我的进口链:

controller.ts -> view.ts -> dragula -> crossvent -> 自定义事件

// Controller.ts:
import { View } from './View';    

// View.ts: 
const dragula = require('dragula');

// dragula requires crossvent, which requires custom-event, which does this:
module.exports = useNative() ? NativeCustomEvent :

'function' === typeof document.createEvent ? function CustomEvent (type, params) { 
    var e = document.createEvent('CustomEvent');
    // ...
} : function CustomEvent (type, params) {
    // ...
}

// controller.spec.ts:
import { Controller } from '../../src/Controller';

我得到的错误:

ReferenceError: 文档未定义

尝试用proxyquire 模拟View,如下所示:

beforeEach( () => {
    viewStub = {};
    let view:any = proxyquire('../../src/View', { 'View': viewStub });
    viewStub.constructor = function():void { console.log('hello!'); };

});

我的问题是,由于 import 语句,甚至在 View 初始化之前就会弹出错误。

【问题讨论】:

    标签: unit-testing typescript mocha.js proxyquire


    【解决方案1】:

    如果你在像 Node 这样没有定义全局文档的环境中运行,你可以创建一个类似这样的存根文档

    // ensure-document.ts
    if (typeof global !== 'undefined' && !global.document) {
      global.document = {};
    }
    

    您需要在导入控制器之前执行此代码,这意味着

    // controller.spec.ts:
    import './ensure-document';
    
    import { Controller } from '../../src/Controller';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 2013-07-07
      相关资源
      最近更新 更多