项目作者: DevHelp-Online

项目描述 :
Mock window | document | global objects in Node. Prevent common Node errors while doing JS Server-side rendering by stubbing out global & window objects for Node.
高级语言: TypeScript
项目地址: git://github.com/DevHelp-Online/create-node-mocks.git
创建时间: 2018-10-07T23:09:57Z
项目社区:https://github.com/DevHelp-Online/create-node-mocks

开源协议:MIT License

下载


Mock Window & Document in NodeJS

Perfect for Angular Universal or any SSR Applications

npm version

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!

Installation

Install & save the library to your package.json:

  1. $ npm i -S @devhelponline/create-node-mocks

Useage

Within your main Node file (regardless of framework)

  1. import { createNodeMocks } from '@devhelponline/create-node-mocks';
  2. import { readFileSync } from 'fs';
  3. import { join } from 'path';
  4. // Grab your index.html Template for us to create a Domino wrapper around
  5. // In this case, we're grabbing it for an Angular-CLI 6+ project
  6. const template = readFileSync(join(DIST_FOLDER, 'ANGULAR_CLI_PROJECT_NAME', 'index.html')).toString();
  7. 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.

Add custom Window or (Node) Global mocks

  1. import { createNodeMocks, IMock } from './node-mocks';
  2. import { readFileSync } from 'fs';
  3. import { join } from 'path';
  4. const template = readFileSync(join(DIST_FOLDER, 'ANGULAR_CLI_PROJECT_NAME', 'index.html')).toString();
  5. const noop = () => {};
  6. // Window Mocks
  7. const additionalWindowMocks: IMock = {
  8. alert: () => {},
  9. someWindowObject: {}
  10. };
  11. // Node Global Mocks
  12. // In this example we want to add a few jQuery mocks
  13. const nodeGlobalMocks: IMock = {
  14. jQuery: () => {
  15. return {
  16. addClass: noop,
  17. removeClass: noop,
  18. remove: noop,
  19. click: noop,
  20. html: noop
  21. };
  22. }
  23. };
  24. createNodeMocks(template, additionalWindowMocks, nodeGlobalMocks);

How to Contribute?

To generate all *.js, *.js.map and *.d.ts files:

  1. npm run build

To lint all *.ts files:

  1. npm run lint

License

MIT © Mark Pieszak | DevHelp Online

Twitter Follow


DevHelp.Online - Angular & ASP.NET - Consulting | Training | Development

Check out www.DevHelp.Online for more info! Twitter @DevHelpOnline

Contact us at hello@devhelp.online, and let’s talk about your projects needs.


DevHelp.Online - Angular ASPNET JavaScript Consulting Development and Training