Angular Universal projects or any JS applications doing SSR where window|document|global objects may be used in Node.
With createNodeMocks() you'll be able to automatically mock & stub out common global (browser-only) APIs such as window | document | navigator
(and others), and easily inject any additional mocks you need!
Install & save the library to your package.json:
$ npm i -S @devhelponline/create-node-mocks
Within your main Node file (regardless of framework)
import { createNodeMocks } from '@devhelponline/create-node-mocks';
import { readFileSync } from 'fs';
import { join } from 'path';
// Grab your index.html Template for us to create a Domino wrapper around
// In this case, we're grabbing it for an Angular-CLI 6+ project
const template = readFileSync(join(DIST_FOLDER, 'ANGULAR_CLI_PROJECT_NAME', 'index.html')).toString();
createNodeMocks(template);
Voila, common window|document errors will gone. Make sure to always wrap these around a test to determine whether this is a Server environment, and ignore them.
import { createNodeMocks, IMock } from './node-mocks';
import { readFileSync } from 'fs';
import { join } from 'path';
const template = readFileSync(join(DIST_FOLDER, 'ANGULAR_CLI_PROJECT_NAME', 'index.html')).toString();
const noop = () => {};
// Window Mocks
const additionalWindowMocks: IMock = {
alert: () => {},
someWindowObject: {}
};
// Node Global Mocks
// In this example we want to add a few jQuery mocks
const nodeGlobalMocks: IMock = {
jQuery: () => {
return {
addClass: noop,
removeClass: noop,
remove: noop,
click: noop,
html: noop
};
}
};
createNodeMocks(template, additionalWindowMocks, nodeGlobalMocks);
To generate all *.js
, *.js.map
and *.d.ts
files:
npm run build
To lint all *.ts
files:
npm run lint
MIT © Mark Pieszak | DevHelp Online
Check out www.DevHelp.Online for more info! Twitter @DevHelpOnline
Contact us at [email protected], and let's talk about your projects needs.