• Stars
    star
    8,971
  • Rank 3,849 (Top 0.08 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Monkey testing library for web apps and Node.js

gremlins.js

gremlins

A monkey testing library written in JavaScript, for Node.js and the browser. Use it to check the robustness of web applications by unleashing a horde of undisciplined gremlins.


Generate bookmarklet | Install docs



version downloads Build Status

PRs Welcome Code of Conduct MIT License

Tweet

TodoMVC attacked by gremlins

Kate: What are they, Billy?

Billy Peltzer: They're gremlins, Kate, just like Mr. Futterman said.

Table of Contents

Purpose

While developing an HTML5 application, did you anticipate uncommon user interactions? Did you manage to detect and patch all memory leaks? If not, the application may break sooner or later. If n random actions can make an application fail, it's better to acknowledge it during testing, rather than letting users discover it.

Gremlins.js simulates random user actions: gremlins click anywhere in the window, enter random data in forms, or move the mouse over elements that don't expect it. Their goal: triggering JavaScript errors, or making the application fail. If gremlins can't break an application, congrats! The application is robust enough to be released to real users.

This practice, also known as Monkey testing or Fuzz testing, is very common in mobile application development (see for instance the Android Monkey program). Now that frontend (MV*, d3.js, Backbone.js, Angular.js, etc.) and backend (Node.js) development use persistent JavaScript applications, this technique becomes valuable for web applications.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm i gremlins.js

This library has dependencies listings for chance.

gremlins.js is also available as a bookmarklet. Go to this page, grab it, and unleash hordes on any web page.

Basic Usage

A gremlins horde is an army of specialized gremlins ready to mess up your application. unleash the gremlins to start the stress test:

const horde = gremlins.createHorde();
horde.unleash();
// gremlins will act randomly, at 10 ms interval, 1000 times

gremlins.js provides several gremlin species: some click everywhere on the page, others enter data in form inputs, others scroll the window in every possible direction, etc.

You will see traces of the gremlins actions on the screen (they leave red traces) and in the console log:

gremlin formFiller input 5 in <input type=​"number" name=​"age">​
gremlin formFiller input [email protected] in <input type=​"email" name=​"email">​
gremlin clicker    click at 1219 301
gremlin scroller   scroll to 100 25
...

A horde also contains mogwais, which are harmless gremlins (or, you could say that gremlins are harmful mogwais). Mogwais only monitor the activity of the application and record it on the logger. For instance, the "fps" mogwai monitors the number of frame per second, every 500ms:

mogwai  fps  33.21
mogwai  fps  59.45
mogwai  fps  12.67
...

Mogwais also report when gremlins break the application. For instance, if the number of frames per seconds drops below 10, the fps mogwai will log an error:

mogwai  fps  12.67
mogwai  fps  23.56
err > mogwai  fps  7.54 < err
mogwai  fps  15.76
...

After 10 errors, a special mogwai stops the test. He's called Gizmo, and he prevents gremlins from breaking applications bad. After all, once gremlins have found the first 10 errors, you already know what you have to do to make your application more robust.

If not stopped by Gizmo, the default horde stops after roughly 1 minute. You can increase the number of gremlins actions to make the attack last longer:

const horde = gremlins.createHorde({
    strategies: [gremlins.strategies.allTogether({ nb: 10000 })],
});
horde.unleash();
// gremlins will attack at 10 ms interval, 10,000 times

Gremlins, just like mogwais, are simple JavaScript functions. If gremlins.js doesn't provide the gremlin that can break your application, it's very easy to develop it:

// Create a new custom gremlin to blur an input randomly selected
function customGremlin({ logger, randomizer, window }) {
    // Code executed once at initialization
    logger.log('Input blur gremlin initialized');
    // Return a function that will be executed at each attack
    return function attack() {
        var inputs = document.querySelectorAll('input');
        var element = randomizer.pick(element);
        element.blur();
        window.alert('attack done');
    };
}

// Add it to your horde
const horde = gremlins.createHorde({
    species: [customGremlin],
});

Everything in gremlins.js is configurable ; you will find it very easy to extend and adapt to you use cases.

Advanced Usage

Setting Gremlins and Mogwais To Use In A Test

By default, all gremlins and mogwais species are added to the horde.

You can also choose to add only the gremlins species you want, using a custom configuration object:

gremlins
    .createHorde({
        species: [
            gremlins.species.formFiller(),
            gremlins.species.clicker({
                clickTypes: ['click'],
            }),
            gremlins.species.toucher(),
        ],
    })
    .unleash();

If you just want to add your own gremlins in addition to the default ones, use the allSpecies constant:

gremlins
    .createHorde({
        species: [...gremlins.allSpecies, customGremlin],
    })
    .unleash();

To add just the mogwais you want, use the mogwai configuration and allMogwais() constant the same way.

gremlins.js currently provides a few gremlins and mogwais:

  • clickerGremlin clicks anywhere on the visible area of the document
  • toucherGremlin touches anywhere on the visible area of the document
  • formFillerGremlin fills forms by entering data, selecting options, clicking checkboxes, etc
  • scrollerGremlin scrolls the viewport to reveal another part of the document
  • typerGremlin types keys on the keyboard
  • alertMogwai prevents calls to alert() from blocking the test
  • fpsMogwai logs the number of frames per seconds (FPS) of the browser
  • gizmoMogwai can stop the gremlins when they go too far

Configuring Gremlins

All the gremlins and mogwais provided by gremlins.js are configurable, i.e. you can alter the way they work by injecting a custom configuration.

For instance, the clicker gremlin is a function that take an object as custom configuration:

const customClicker = gremlins.species.clicker({
    // which mouse event types will be triggered
    clickTypes: ['click'],
    // Click only if parent is has class test-class
    canClick: (element) => element.parentElement.className === 'test-class',
    // by default, the clicker gremlin shows its action by a red circle
    // overriding showAction() with an empty function makes the gremlin action invisible
    showAction: (x, y) => {},
});
gremlins.createHorde({
    species: [customClicker],
});

Each particular gremlin or mogwai has its own customization methods, check the source for details.

Seeding The Randomizer

If you want the attack to be repeatable, you need to seed the random number generator :

// seed the randomizer
horde.createHorde({
    randomizer: new gremlins.Chance(1234);
});

Executing Code Before or After The Attack

Before starting the attack, you may want to execute custom code. This is especially useful to:

  • Start a profiler
  • Disable some features to better target the test
  • Bootstrap the application

Fortunately, unleashHorde is a Promise. So if you want to execute code before and after the unleash just do:

const horde = gremlins.createHorde();

console.profile('gremlins');
horde.unleash().then(() => {
    console.profileEnd();
});

Setting Up a Strategy

By default, gremlins will attack in random order, in a uniform distribution, separated by a delay of 10ms. This attack strategy is called the distribution strategy. You can customize it using the strategies custom object:

const distributionStrategy = gremlins.strategies.distribution({
    distribution: [0.3, 0.3, 0.3, 0.1], // the first three gremlins have more chances to be executed than the last
    delay: 50, // wait 50 ms between each action
});

Note that if using default gremlins, there are five type of gremlins. The previous example would give a 0 value to last gremlin specie.

You can also use another strategy. A strategy is just a function expecting one parameter: an array of gremlins. Two other strategies are bundled (allTogether and bySpecies), and it should be fairly easy to implement a custom strategy for more sophisticated attack scenarios.

Stopping The Attack

The horde can stop the attack in case of emergency using the horde.stop() method Gizmo uses this method to prevent further damages to the application after 10 errors, and you can use it, too, if you don't want the attack to continue.

Customizing The Logger

By default, gremlins.js logs all gremlin actions and mogwai observations in the console. If you prefer using an alternative logging method (for instance, storing gremlins activity in LocalStorage and sending it in Ajax once every 10 seconds), just provide a logger object with 4 methods (log, info, warn, and error) to the logger() method:

const customLogger = {
    log: function (msg) {
        /* .. */
    },
    info: function (msg) {
        /* .. */
    },
    warn: function (msg) {
        /* .. */
    },
    error: function (msg) {
        /* .. */
    },
};
horde.createHorde({ logger: customLogger });

Cypress

To run gremlins.js inside a cypress test, you need to provide the tested window:

import { createHorde } from 'gremlins.js';

describe('Run gremlins.js inside a cypress test', () => {
    let horde;
    beforeEach(() =>
        cy.window().then((testedWindow) => {
            horde = createHorde({ window: testedWindow });
        })
    );
    it('should run gremlins.js', () => {
        return cy.wrap(horde.unleash()).then(() => {
            /* ... */
        });
    });
});

Playwright

To run gremlin.js with Playwright, you can load it as an init script.

const { test } = require('@playwright/test');

test('run gremlins.js', async ({ page }) => {
    await page.addInitScript({
        path: './node_modules/gremlins.js/dist/gremlins.min.js',
    });
    await page.goto('https://playwright.dev');
    await page.evaluate(() => gremlins.createHorde().unleash());
});

Docs

Issues

Looking to contribute? Look for the Good First Issue label.

🐛 Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.

See Feature Requests

License

gremlins.js is licensed under the MIT Licence, courtesy of marmelab.

More Repositories

1

react-admin

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design
TypeScript
22,823
star
2

ng-admin

Add an AngularJS admin GUI to any RESTful API
JavaScript
3,968
star
3

awesome-rest

A collaborative list of great resources about RESTful API architecture, development, test, and performance
3,457
star
4

json-graphql-server

Get a full fake GraphQL API with zero coding in less than 30 seconds.
JavaScript
1,911
star
5

universal.css

The only CSS you will ever need
CSS
1,260
star
6

EventDrops

A time based / event series interactive visualization using d3.js
JavaScript
1,236
star
7

restful.js

A pure JS client for interacting with server-side RESTful resources. Think Restangular without Angular.
JavaScript
969
star
8

gaudi

Gaudi allows to share multi-component applications, based on Docker, Go, and YAML.
Go
566
star
9

ng-admin-react

Add a ReactJS admin GUI to any RESTful API. Deprecated: see admin-on-rest for a full rewrite
JavaScript
544
star
10

FakeRest

Patch fetch/XMLHttpRequest to fake a REST API server in the browser, based on JSON data.
JavaScript
407
star
11

admin-on-rest

A frontend framework for building admin SPAs on top of REST services, using React and Material Design.
JavaScript
400
star
12

admin-on-rest-demo

Source of the admin-on-rest react.js demo, using a dummy REST service powered by FakeRest
JavaScript
329
star
13

ng-admin-demo

Source of the ng-admin angular.js demo, using a dummy REST service powered by FakeRest
JavaScript
305
star
14

sedy

A GitHub bot bringing the sed command to code reviews
JavaScript
266
star
15

javascript-boilerplate

Node.js+Koa.js+PostgreSQL+React.js+Webpack+Mocha+Makefile, a starter kit for new apps
JavaScript
253
star
16

ArchitectureTree

Draw and share your software architecture without diagramming software. Uses d3.js and Angular.js.
JavaScript
218
star
17

comfygure

Encrypted and versioned configuration store built with collaboration in mind
JavaScript
192
star
18

microrest.php

A micro web application providing a REST API on top of any relational database, using Silex and Doctrine DBAL
PHP
186
star
19

graphql-schema-from-json

Guess a GraphQL schema from json data
JavaScript
182
star
20

tree.js

Tree.js is a JavaScript library to build and manipulate hookable trees.
JavaScript
148
star
21

greenframe-cli

Estimate the carbon footprint of a user scenario on a web application
TypeScript
137
star
22

ra-supabase

Supabase adapter for react-admin, the frontend framework for building admin applications on top of REST/GraphQL services.
TypeScript
127
star
23

ng-admin-postgrest

Demo of an integration between ng-admin and PostgREST
JavaScript
111
star
24

phpcr-browser

Web interface for browsing PHPCR repositories, using Silex and AngularJS
CSS
103
star
25

sketch-by-phone

A proof-of-concept of Augmented Reality with HTML5
JavaScript
97
star
26

ArcheoloGit

Where should you focus the maintenance efforts? ArcheoloGit is a visualization of age and dev activity for software, powered by d3.js.
JavaScript
95
star
27

phpunit-d3-report

Visualize the slowest parts of a PHPUnit testsuite using d3.js
JavaScript
93
star
28

GraphQL-example

An example code structure for a GraphQL-powered mobile app. Contains client and server code.
JavaScript
86
star
29

make-docker-command

Seamlessly execute commands (composer, bower, compass) in isolation using docker and make.
Makefile
83
star
30

aor-graphql

Packages related to using GraphQL with Admin-on-rest
JavaScript
81
star
31

react-admin-demo

Source of the react-admin react.js demo, using a dummy REST service powered by FakeRest
67
star
32

ra-auth-acl

Access Control List authProvider and helpers for React Admin
TypeScript
64
star
33

aor-dependent-input

A component for displaying input depending on other inputs values in Admin-on-rest
JavaScript
60
star
34

argos

docker monitoring experiment
58
star
35

react-md-motion

Material design motions with react
JavaScript
54
star
36

Raphael.InlineTextEditing

Raphael Plugin allowing inline edition of SVG text elements
JavaScript
54
star
37

ra-example-oauth

An example of OpenID Connect implementation on React Admin
TypeScript
53
star
38

aor-simple-graphql-client

A simple GraphQL client for admin-on-rest
JavaScript
48
star
39

ZeroDollarHomePage

A decentralized ad server running on the blockchain
JavaScript
45
star
40

SonataElasticaBundle

Power the Sonata Admin list view and filters by an ElasticSearch index to speed up navigation.
PHP
43
star
41

aor-permissions

A component for Admin-on-rest allowing to switch views depending on user permissions. Eg: having different PostEdit components for different users
JavaScript
42
star
42

react-admin-crm

A CRM build with react-admin, used as a demo for the capabilities of the framework
HTML
40
star
43

ra-in-memory-jwt

Manage React-admin authentication with jwt in memory, not in local storage
JavaScript
39
star
44

koa-multifetch

A Koa.js middleware for performing internal batch requests
JavaScript
36
star
45

gollabedit

Experimental collaborative editor written in Go
Go
33
star
46

admin-config

Configuration API to describe an administration interface. Used by ng-admin and react-admin.
JavaScript
31
star
47

ocaml-invader

Ocaml Space-Invader implementation using OpenGL
OCaml
29
star
48

admin-on-rest-graphql-demo

JavaScript
29
star
49

ra-data-google-sheets

A data provider for react-admin, based on Google Sheets
JavaScript
26
star
50

ra-datagrid

Integration of Material-ui's <Datagrid> into react-admin
TypeScript
26
star
51

battery-friendly-timer

Mobile applications using setInterval to poll a server are a battery hogs. Save battery life by fetching data at the right moment.
JavaScript
25
star
52

MobileInsight

A Mobile web app to browse PHP code analyses made by SensioLabsInsight, built with Angular.js and Ionic.
JavaScript
25
star
53

yolo

Typo-tolerant runtime object proxy for fast JavaScritp typers
JavaScript
24
star
54

aor-rich-text-input

<RichTextInput> component for admin-on-rest, useful for editing HTML code in admin GUIs
CSS
23
star
55

timeline-react-admin

Support for a tutorial about custom List views with react-admin
JavaScript
23
star
56

strapi-beerdex

StrapiJS Example Application For Beer Management
JavaScript
23
star
57

chrome-bug-report-wizard

Chrome plugin automating Bug Tracker issue creation with screenshot and browser details
JavaScript
23
star
58

argos-cli

19
star
59

aor-realtime

JavaScript
17
star
60

solid-admin

TypeScript
17
star
61

ra-enterprise-demo

TypeScript
16
star
62

svelte-sse-chat

Chat Example Application Using SvelteJS and Chat
Svelte
15
star
63

uptime

A prototype of website monitoring tool, written in Go and React.js, modeled after fzaninotto/uptime
JavaScript
15
star
64

reactive-beers

Reactive Beers is an example application using CouchDB and PouchDB
JavaScript
15
star
65

reversi-reason

🐪 ReasonML implementation of Reversi Game
OCaml
13
star
66

MobileAudience

Mobile Webapp mixing D3.js with a touch UI ; shows TV audiences and market shares for 8 fictive TV channels across several days.
JavaScript
13
star
67

ng-tree

An Angular.js module for using tree.js
JavaScript
12
star
68

docker-parallel-phpunit-demo

How to use Docker to run PHPUnit tests in parallel
PHP
12
star
69

skelt

{ } Skelt is a simple templating engine for object literals.
JavaScript
12
star
70

redux-form-inspector

An HOC for computing dynamic props from values inside an existing redux-form component.
JavaScript
12
star
71

virothello

💫 Othello Game Using Augmented Reality And Viro
JavaScript
12
star
72

coPostgresQuery

Query builder for PostgreSQL in Node.js, built for async
JavaScript
11
star
73

phpcr-api

PHP
11
star
74

svg_to_png

Convert an SVG file to a PNG image. Uses headless Chrome for rendering.
JavaScript
11
star
75

aor-json-rest-client

A local REST client for admin-on-rest
JavaScript
10
star
76

ra-keycloak

TypeScript
10
star
77

docker-compass

Dockerfile
10
star
78

dobble

Generate a valid deck of cards for Dobble in ECMAScript6
JavaScript
10
star
79

ra-sqlite-dataprovider

POC of a dataprovider using a sqlite database hosted on a static server
JavaScript
9
star
80

checkoid

Experimental validator library allowing to combine validator like you would lego piece.
TypeScript
9
star
81

gql-profiler

A standalone performance profiler for GraphQL resolvers
JavaScript
9
star
82

liMonade

A Monad library to make Monad simple.
TypeScript
9
star
83

dedale

A wood labyrinth game in the browser
JavaScript
9
star
84

curator-ai

An AI-powered news curator. It reads a list of articles, selects the best ones depending on a list of interests, and summarizes them into an easy-to-read news feed. Powered by the OpenAI API.
TypeScript
9
star
85

silex-multifetch

A Silex provider for performing internal batch requests
PHP
9
star
86

treedu

Graphical Disk Usage command for the terminal, using Node.js, d3.js, blessed, and Drawille
JavaScript
9
star
87

ra-auth-cognito

An auth provider for [react-admin](https://github.com/marmelab/react-admin) which handles authentication with AWS [Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html).
TypeScript
9
star
88

docker-composer-hhvm

8
star
89

Asteroids.js

A one day experiment to bringing the Asteroids game to the browser, using a mobile device as controller, Node.js, Raphaël, and socket.io.
JavaScript
8
star
90

docker-bower

Dockerfile
8
star
91

ra-richtext-tiptap

TypeScript
7
star
92

puppeteer-accessibility

JavaScript
7
star
93

web-myna

Record then emulate your api.s for testing and development
JavaScript
7
star
94

ninja-coder

Code with your entire body like a Ninja
JavaScript
7
star
95

configurable.js

A small JS snippet to make a function configurable through its closure
JavaScript
7
star
96

gif-to-webm

Convert GIF files to WebM and replace links to them in doc files
TypeScript
6
star
97

sg

Side Effect Handling library - Think Redux-Saga without Redux
JavaScript
6
star
98

selenium-smart-wait

JavaScript
6
star
99

dobble-php

PHP
6
star
100

marriage-algorithms

Experiments with stable marriage algorithms
TypeScript
6
star