I need to somehow mock the document object to be able to unit-test a legacy TypeScript class. The class imports another class (View.ts), which has an import of a 3-rd party module, and that, in turn, imports something else which assumes document exists.
My chain of imports:
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';
Error I'm getting:
ReferenceError: document is not defined
Tried mock the View with proxyquire, like this:
beforeEach( () => {
    viewStub = {};
    let view:any = proxyquire('../../src/View', { 'View': viewStub });
    viewStub.constructor = function():void { console.log('hello!'); };
});
My problem is that error pops up even before the View gets initialized, due to import statements.
If you are running in an environment like 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';
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With