Unit test: document layout used by imported TypeScript dependency?

I need to somehow mock the document object in order to be able to debug an obsolete TypeScript class. The class imports another class ( View.ts ), which has an import of the 3rd party module and, in turn, imports something else that assumes document .

My import chain:

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

The error I get is:

ReferenceError: document not defined

Tried View with proxyquire , for example:

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

My problem is that the error appears even before the View initialized, due to import statements.

+7
unit-testing typescript mocha proxyquire
source share
1 answer

If you work in an environment such as Node that does not define a global document, you can create a stub document with something like this

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

You need to execute this code before importing the controller, which means something like

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

All Articles