我需要以某种方式模拟 document
对象,以便能够对遗留 TypeScript 类进行单元测试。该类导入另一个类 (View.ts
),该类具有第 3 方模块的 import
,而该类又导入其他假定 >文档
存在。
我的进口链:
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 is not defined
尝试用 proxyquire 模拟 View
,像这样:
beforeEach( () => {
viewStub = {};
let view:any = proxyquire('../../src/View', { 'View': viewStub });
viewStub.constructor = function():void { console.log('hello!'); };
});
我的问题是,由于 import
语句,错误甚至在 View
初始化之前就弹出。
最佳答案
如果你在像 Node 这样没有定义全局文档的环境中运行,你可以用这样的东西创建一个 stub 文档
// ensure-document.ts
if (typeof global !== 'undefined' && !global.document) {
global.document = {};
}
您需要在导入 Controller 之前执行此代码,这意味着类似
// controller.spec.ts:
import './ensure-document';
import { Controller } from '../../src/Controller';
关于unit-testing - 单元测试 : mock document used by an imported TypeScript dependency?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41104268/