7

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.

1 Answer 1

1

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';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.