7

我需要以某种方式模拟该document对象,以便能够对遗留的 TypeScript 类进行单元测试。该类导入另一个类View.tsimportdocument

我的进口链:

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:文档未定义

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

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

});

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

4

1 回答 1

1

如果您在像 Node 这样没有定义全局文档的环境中运行,您可以使用类似这样的内容创建存根文档

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

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

// controller.spec.ts:
import './ensure-document';

import { Controller } from '../../src/Controller';
于 2016-12-18T14:33:55.300 回答