Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test: mock document used by an imported TypeScript dependency?

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.

like image 704
montrealist Avatar asked Dec 12 '16 15:12

montrealist


1 Answers

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';
like image 70
Aluan Haddad Avatar answered Oct 22 '22 12:10

Aluan Haddad