单元测试:如何模拟导入的 TypeScript 依赖项使用的文档?

7

我需要以某种方式模拟document对象,以便对遗留的TypeScript类进行单元测试。该类导入另一个类(View.ts),该类有一个第三方模块的import,而该模块又会导入假设document存在的其他内容。

我的导入链如下:

controller.ts -> view.ts -> dragula -> crossvent -> custom-event

// 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: document未定义

我试图使用proxyquire来模拟View,像这样:

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

});

我的问题是,由于import语句的存在,即使在View初始化之前,错误也会弹出。

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';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接