I am writing some unit tests in TypeScript 2.4.2 for a library written in the same language.
Some test case require access to properties such document.location.href
, so I need to mock the DOM.
The test runner is Mocha and the assertion framework is Chai.
Asked
Active
Viewed 2,300 times
1

JBENOIT
- 421
- 3
- 14
-
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. Use the "edit" link to improve your *question* - do not add more information via comments. Thanks! – GhostCat Aug 08 '17 at 09:29
-
**Doesnt work** isnt a working problem description for us. Consider putting up that [mcve] and clearly describing in which way "it doesnt work" and fails your expectations. – GhostCat Aug 08 '17 at 09:29
-
1@GhostCat I just edit my question. My problem is not about a specific code but more "how to do that". – JBENOIT Aug 08 '17 at 09:35
1 Answers
3
Well, after many hours of headache and this post on SO, I finally find a way to do it:
- Install the jsdom-global and jsdom module:
npm install --save-dev jsdom jsdom-global
- Create a file named
dom-mock.js
, for example. - In this file, add this:
require('jsdom-global')(/* any html you need */, {
/* any jsdom options you need, e.g: */
url: "https://example.org/",
referrer: "https://example.com/"
});
- Run the tests by registering the dom mock you just created:
mocha -r tests/mocks/dom-mock.js -r ts-node/register tests/*.ts
If you do not need DOM customization, just run mocha -r jsdom-global/register -r ts-node/register tests/*.ts

JBENOIT
- 421
- 3
- 14