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

1

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.

Garibold answered 12/12, 2016 at 15:34 Comment(0)
B
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';
Billiot answered 18/12, 2016 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.