Repository: marmelab/gremlins.js Branch: master Commit: cbcd182f2d76 Files: 59 Total size: 104.8 KB Directory structure: gitextract__jhz54jw/ ├── .babelrc ├── .eslintignore ├── .eslintrc.js ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ ├── config.yml │ │ ├── feature_request.md │ │ └── question.md │ ├── ISSUE_TEMPLATE.md │ └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .npmrc ├── .prettierignore ├── .prettierrc ├── .travis.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── bookmarklet/ │ ├── index.css │ └── index.html ├── cypress/ │ ├── fixtures/ │ │ └── example.json │ ├── integration/ │ │ └── formFiller.spec.js │ ├── pages/ │ │ └── formFiller.html │ ├── plugins/ │ │ └── index.js │ └── support/ │ ├── commands.js │ └── index.js ├── cypress.json ├── jest.config.js ├── package.json ├── rollup.config.js └── src/ ├── index.js ├── mogwais/ │ ├── alert.js │ ├── alert.spec.js │ ├── fps.js │ ├── fps.spec.js │ ├── gizmo.js │ └── gizmo.spec.js ├── species/ │ ├── clicker.js │ ├── clicker.spec.js │ ├── formFiller.js │ ├── formFiller.spec.js │ ├── scroller.js │ ├── scroller.spec.js │ ├── toucher.js │ ├── toucher.spec.js │ ├── typer.js │ └── typer.spec.js ├── strategies/ │ ├── allTogether.js │ ├── allTogether.spec.js │ ├── bySpecies.js │ ├── bySpecies.spec.js │ ├── distribution.js │ └── distribution.spec.js └── utils/ ├── executeInSeries.js ├── executeInSeries.spec.js ├── wait.js └── wait.spec.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "env": { "test": { "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ] ] } }, "presets": [ [ "@babel/preset-env", { "useBuiltIns": "usage", "shippedProposals": true, "corejs": 3, "targets": { "browsers": ["last 2 major versions", "not dead", "not IE 11"] } } ] ] } ================================================ FILE: .eslintignore ================================================ node_modules dist package-lock.json ================================================ FILE: .eslintrc.js ================================================ module.exports = { env: { node: true, browser: true, es2020: true, }, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2020, sourceType: 'module', }, plugins: ['prettier', 'babel'], extends: [ 'eslint:recommended', 'prettier', 'plugin:prettier/recommended', 'plugin:import/errors', 'plugin:import/warnings', 'plugin:jest/recommended', 'plugin:jest/style', 'plugin:cypress/recommended', ], rules: { 'prettier/prettier': 'error', 'babel/no-unused-expressions': 'error', }, overrides: [ { files: ['cypress/integration/*.spec.js'], rules: { 'jest/expect-expect': 'off', }, }, ], }; ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: '🐛 Bug Report' about: Bugs, missing documentation, or unexpected behavior 🤔. title: 'Bug: ' --- - `gremlins.js` version: - `node` version: - `npm` (or `yarn`) version: - browser version: ## Steps To Reproduce 1. 2. Link to code example: ## The current behavior ## The expected behavior ### Suggested solution: ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: 📝 Code of Conduct url: https://github.com/marmelab/gremlins.js/blob/master/CODE_OF_CONDUCT.md about: ❤ Be nice to other members of the community. ☮ Behave. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: 💡 Feature Request about: I have a suggestion (and might want to implement myself 🙂)! --- ### Describe the feature you'd like: ### Suggested implementation: ### Describe alternatives you've considered: ### Teachability, Documentation, Adoption, Migration Strategy: ================================================ FILE: .github/ISSUE_TEMPLATE/question.md ================================================ --- name: ❓ Question about: Ask a question not related to implementation here label: question --- 🚨 The issue tracker is not for implementation questions 🚨 ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ 👉 Please follow one of these issue templates: - https://github.com/marmelab/gremlins.js/issues/new/choose Note: to keep the backlog clean and actionable, issues may be immediately closed if they do not follow one of the above issue templates. ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ **What**: **Why**: **How**: **Checklist**: - [ ] Documentation added to the README.md file - [ ] Tests - [ ] Typescript definitions updated - [ ] RFR, Ready for review label ================================================ FILE: .gitignore ================================================ dist node_modules npm-debug.log cypress/screenshots ================================================ FILE: .npmrc ================================================ registry=https://registry.npmjs.org/ ================================================ FILE: .prettierignore ================================================ node_modules dist package-lock.json ================================================ FILE: .prettierrc ================================================ { "tabWidth": 4, "singleQuote": true, "printWidth": 120 } ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - node # Current stable - lts/* # Most recent LTS version install: - npm ci script: - npm run test - npm run cypress:run branches: only: - master - next ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## [2.2.0](https://github.com/marmelab/gremlins.js/compare/v2.1.1...v2.2.0) (2020-07-21) ### Features - add formFiller cypress test ([e278b5b](https://github.com/marmelab/gremlins.js/commit/e278b5bf10eec1ed7e71cae0dc7a641e7971540f)) - allow to pass a custom window to gremlins ([9a2084c](https://github.com/marmelab/gremlins.js/commit/9a2084c668f68be3285633e987889839dab190da)) - bump standard-version to 8.0.2 ([ed60ec6](https://github.com/marmelab/gremlins.js/commit/ed60ec6b0f1a498479c2eb29205eaaa81a2c5341)) - update readme with cypress usage ([005373e](https://github.com/marmelab/gremlins.js/commit/005373efd3cd52427b7220b3c3befe5a3d08053b)) ### Bug Fixes - bad practice in readme ([d0528ab](https://github.com/marmelab/gremlins.js/commit/d0528ab60b1887c55a5226cf7a6d95b121fdf942)) - cypress plugins ([8ec3047](https://github.com/marmelab/gremlins.js/commit/8ec304755a3a8d1ae3d86da688c81b658d8158d3)) - linter conf ([22ca500](https://github.com/marmelab/gremlins.js/commit/22ca500d1d0d82e01ada08a800fbea37bc40d6d8)) - pass window to gremlins ([9898e41](https://github.com/marmelab/gremlins.js/commit/9898e41d53fe82a4b26145757816e07a754d7da5)) - remove useless command in package.json ([c7f3243](https://github.com/marmelab/gremlins.js/commit/c7f3243ee04d49c14efcabc9078c76e82e18ad16)) - remove useless fixture ([1166503](https://github.com/marmelab/gremlins.js/commit/11665031ef341d4bee9c5208604c7334bd27c3de)) - remove useless make command ([b00e703](https://github.com/marmelab/gremlins.js/commit/b00e703c74f3659246af627adf6476993fc92f70)) ### [2.1.1](https://github.com/marmelab/gremlins.js/compare/v2.1.0...v2.1.1) (2020-04-27) ### Bug Fixes - add hmtl prototype for numbers elements ([e415936](https://github.com/marmelab/gremlins.js/commit/e4159365515fb1068e6f0a98e4c008e79d7e6653)) ## [2.1.0](https://github.com/marmelab/gremlins.js/compare/v2.0.1...v2.1.0) (2020-04-22) ### Features - make scroll signal unclickable ([e526549](https://github.com/marmelab/gremlins.js/commit/e52654911dc2c3d7b6d8adb134ba916a6937a938)) ### Bug Fixes - chance RangeError ([3856336](https://github.com/marmelab/gremlins.js/commit/38563366603c39a759a5df6c04195ffb5217738a)) ### [2.0.1](https://github.com/marmelab/gremlins.js/compare/v2.0.0...v2.0.1) (2020-04-08) ## [2.0.0](https://github.com/marmelab/gremlins.js/compare/v2.0.0-next.2...v2.0.0) (2020-04-08) ### Features - add customisable bookmarklet ([96db4be](https://github.com/marmelab/gremlins.js/commit/96db4be3608068a0ff56390859d6c2e0c54dce10)) - add guide, issue, bug template ([16016df](https://github.com/marmelab/gremlins.js/commit/16016df1219aab461d0a79d2e9fc3059ae286212)) - expose gremlins in bookmarklet page ([a03d429](https://github.com/marmelab/gremlins.js/commit/a03d429ad95e87f45889aa2bd0f1db1fc44aef86)) - refaco executeInSeries function ([aa03316](https://github.com/marmelab/gremlins.js/commit/aa03316df05419bfa811cda3d4800570dce6ac5b)) - update babel and rolup dep ([d6b439b](https://github.com/marmelab/gremlins.js/commit/d6b439b8637d8057673cd61c7b21b091dc8b4fa1)) - update readme ([ae11c93](https://github.com/marmelab/gremlins.js/commit/ae11c937f7f3bc92aff61644dca60998df971ca1)) - update seed, stop and custom logger documentation ([13c9920](https://github.com/marmelab/gremlins.js/commit/13c99203cf2712248ffceb4cde80d705096c1787)) - update to prettier 2.0 and eslint last version ([af374d4](https://github.com/marmelab/gremlins.js/commit/af374d4a5dd5789eacec5d543f6d0fe7ec335e62)) ### Bug Fixes - change next to master branch ([f66ffeb](https://github.com/marmelab/gremlins.js/commit/f66ffebc20715c386b087f88c35b75e4b0112cf3)) - illegal invocation on text area ([a877e46](https://github.com/marmelab/gremlins.js/commit/a877e46245292fa068eb209ed69f6a1f88d5b337)) - simulated on change usage ([24ea017](https://github.com/marmelab/gremlins.js/commit/24ea017b0b20e00403adace3caf17df1ea4b416a)) - toucher log test ([c7f2abd](https://github.com/marmelab/gremlins.js/commit/c7f2abdbc7c8a870241144d34675de4fa4d7a61f)) - typo in readme ([9cbb8e5](https://github.com/marmelab/gremlins.js/commit/9cbb8e553047739e7ff8b77f5f3ce20804afb144)) - update babel to fix test on node 13.10.1 ([ffc6542](https://github.com/marmelab/gremlins.js/commit/ffc654235c577d54e69bfbbc02b2b55242525a52)) - use fake timers usage ([c404ed8](https://github.com/marmelab/gremlins.js/commit/c404ed81941d361e6fb1845573054336f10a1462)) ## [2.0.0-next.2](https://github.com/marmelab/gremlins.js/compare/v2.0.0-next.1...v2.0.0-next.2) (2020-02-26) ### Features - add bookmarklet.html file ([96b26a0](https://github.com/marmelab/gremlins.js/commit/96b26a080605d42149afa669447523ff774b5b1a)) - deploy to gh-pages ([2399363](https://github.com/marmelab/gremlins.js/commit/2399363ac114037a5292d520eeb55e5883cdaaeb)) ### Bug Fixes - custom config, logger & exceptions ([fc1ca4b](https://github.com/marmelab/gremlins.js/commit/fc1ca4b7728227f463a4c49706c66f237df24c88)) ## [2.0.0-next.1](https://github.com/marmelab/gremlins.js/compare/v2.0.0-next...v2.0.0-next.1) (2020-02-26) ### Features - add standard-version package ([137eb96](https://github.com/marmelab/gremlins.js/commit/137eb96e4f635fb6f5a1bc348dce430dfa31c990)) - change bundle name to gremlins and fix strategies stop ([6203ed4](https://github.com/marmelab/gremlins.js/commit/6203ed4f34040247672f1e436b19278c84759ecb)) - clean up code and use object for config ([a12e779](https://github.com/marmelab/gremlins.js/commit/a12e77983d19f8951261a5dd9e694ae75943694e)) - migrate form filler ([f9a7698](https://github.com/marmelab/gremlins.js/commit/f9a7698c88ead3f9b908e57e58f1e45bb2b8a999)) - migrate mogwais and delete configurable ([e87de74](https://github.com/marmelab/gremlins.js/commit/e87de74608510a9b8b5c96a3e50ffe6d0fdc9686)) - migrate scroller ([72ee515](https://github.com/marmelab/gremlins.js/commit/72ee515ed25a7694c6b9a5d79a67b7ac39619da4)) - migrate strategies ([b300076](https://github.com/marmelab/gremlins.js/commit/b3000764f5acf6623e969944152db640868220aa)) - migrate toucher ([bbec05c](https://github.com/marmelab/gremlins.js/commit/bbec05c221599d9dbf15628b465f27df45f38c7d)) - migrate typer ([50eaa3b](https://github.com/marmelab/gremlins.js/commit/50eaa3b54f3f3763234f153d31aefb5fc0c3886d)) - use object config ([7876644](https://github.com/marmelab/gremlins.js/commit/7876644f5d4cac10b4803d6c4c94177b47efe08d)) ### Bug Fixes - const names ([7d57872](https://github.com/marmelab/gremlins.js/commit/7d578723c447fccc6bd31776601ac407dc73c352)) - remove unused parameter from executeInSeries ([a85a9bf](https://github.com/marmelab/gremlins.js/commit/a85a9bf75897f8e3c690981ae19e459b9130de30)) ## [2.0.0-next.0](https://github.com/marmelab/gremlins.js/compare/v2.0.0-next...v2.0.0-next.0) (2020-02-26) ### Features - add standard-version package ([137eb96](https://github.com/marmelab/gremlins.js/commit/137eb96e4f635fb6f5a1bc348dce430dfa31c990)) ## [2.0.0-next](https://github.com/marmelab/gremlins.js/compare/v0.1.0...v2.0.0-next) (2020-02-26) ### Features - add commitlint convention ([b1e7d03](https://github.com/marmelab/gremlins.js/commit/b1e7d03aae45de6aa37c26e00fed59bd39600218)) - add sourcemap on production build ([275a296](https://github.com/marmelab/gremlins.js/commit/275a2961283ac0adafc45a662cfdc1886696f7ac)) - add travis CI ([1d5fc5e](https://github.com/marmelab/gremlins.js/commit/1d5fc5ece866fa1373ca224dde0a431221ba271c)) - bootstrap rollup ([677ba03](https://github.com/marmelab/gremlins.js/commit/677ba0318708da2780a1288124dc2d424f5130f1)) - bootstrap test with jest ([13398a6](https://github.com/marmelab/gremlins.js/commit/13398a680774e2035d1b9757f24f3999a96ae278)) - eslint update dep ([ab83723](https://github.com/marmelab/gremlins.js/commit/ab83723d82bcf423afd06a1f9294ad782a234b52)) - update babel, webpack and chance dep ([69b6567](https://github.com/marmelab/gremlins.js/commit/69b6567e4292e9cad2e8614fa7b26d10d58d680b)) # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: - Demonstrating empathy and kindness toward other people - Being respectful of differing opinions, viewpoints, and experiences - Giving and gracefully accepting constructive feedback - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience - Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: - The use of sexualized language or imagery, and sexual attention or advances of any kind - Trolling, insulting or derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or email address, without their explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: CONTRIBUTING.md ================================================ # Contribution Yeay! You want to contribute to gremlins.js. That's amazing! To smoothen everyone's experience involved with the project please take note of the following guidelines and rules. ## Found an Issue? Thank you for reporting any issues you find. We do our best to test and make gremlins.js as solid as possible, but any reported issue is a real help. Please follow these guidelines when reporting issues: - Tag your issue with the tag `bug` - Provide a short summary of what you are trying to do - Provide the log of the encountered error if applicable - Provide the exact version of gremlins.js. Check `npm ls gremlins.js` when in doubt - Be awesome and consider contributing a [pull request](#want-to-contribute) ## Want to contribute? You consider contributing changes to gremlins.js – we dig that! Please consider these guidelines when filing a pull request: - Follow the [Coding Rules](#coding-rules) - Follow the [Commit Rules](#commit-rules) - Make sure you rebased the current master branch when filing the pull request - Squash your commits when filing the pull request - Provide a short title with a maximum of 100 characters - Provide a more detailed description containing _ What you want to achieve _ What you changed _ What you added _ What you removed ## Coding Rules To keep the code base of gremlins.js neat and tidy the following rules apply to every change - `eslint` and `prettier` is king, use `make lint` and `make format` - Be awesome ## Commit Rules To help everyone with understanding the commit history of gremlins.js the following commit rules are enforced. We follow the [conventional commit messages](https://www.conventionalcommits.org/en/v1.0.0/) convention in order to automate CHANGELOG generation and to automate semantic versioning. For example: - `feat: A new feature` - `fix: A bug fix` Commits types such as as `docs:`,`style:`,`refactor:`,`perf:`,`test:` and `chore:` are valid but have no effect on versioning. **It would be great if you use them.** All commits message are going to be validated when they are created using husky hooks. **PRs that do not follow the commit message guidelines will not be merged.** ================================================ FILE: LICENSE ================================================ Copyright (c) 2014 marmelab Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Makefile ================================================ help: @grep -P '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' install: ## Install dependencies npm install start: ## Rollup watch the project npm run start build: clear ## Rollup build the project npm run build clear: ## Clear dist directory npm run clear test: ## Run whole tests npm run test test-cypress: ## Run cypress tests npm run cypress:run test-watch: ## Watch whole test suites npm run test:watch lint: ## lint the code and check coding conventions echo "Running linter..." npm run lint format: ## prettify the source code using prettier echo "Running prettier..." npm run format serve: build ## Serve dist directory npm run serve publish: ## Publish npm run release publish-dry-run: ## Publish dry-run npm run release -- --dry-run publish-next: ## Publish on next tag npm run release -- --prerelease next deploy-gh-pages: ## Deploy bookmaklet to gh-pages npm run deploy-gh-pages ================================================ FILE: README.md ================================================

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**](https://marmelab.com/gremlins.js/) | [Install docs](#Installation)

[![version](https://img.shields.io/npm/v/gremlins.js.svg?style=flat-square)](https://www.npmjs.com/package/gremlins.js) [![downloads](https://img.shields.io/npm/dm/gremlins.js.svg?style=flat-square)](https://www.npmtrends.com/gremlins.js) [![Build Status](https://img.shields.io/travis/marmelab/gremlins.js.svg?style=flat-square)](https://travis-ci.org/github/marmelab/gremlins.js) [![PRs Welcome](https://img.shields.io/badge/prs-welcome-brightgreen.svg?style=flat-square)](https://github.com/marmelab/gremlins.js/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc) [![Code of Conduct](https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square)](https://github.com/marmelab/gremlins.js/blob/master/code_of_conduct.md) [![MIT License](https://img.shields.io/npm/l/gremlins.js.svg?style=flat-square)](https://github.com/marmelab/gremlins.js/blob/master/license) [![Tweet](https://img.shields.io/twitter/url/https/github.com/marmelab/gremlins.js.svg?style=social)](https://twitter.com/intent/tweet?text=check%20out%20gremlins.js%20by%20%40marmelab%20https%3a%2f%2fgithub.com%2fmarmelab%2fgremlins.js%20%f0%9f%91%8d)
TodoMVC attacked by gremlins
> Kate: _What are they, Billy?_ > > Billy Peltzer: _They're gremlins, Kate, just like Mr. Futterman said._ ## Table of Contents - [Purpose](#purpose) - [Installation](#installation) - [Basic Usage](#basic-usage) - [Advanced Usage](#advanced-usage) - [Setting Gremlins and Mogwais To Use In A Test](#setting-gremlins-and-mogwais-to-use-in-a-test) - [Configuring Gremlins](#configuring-gremlins) - [Seeding The Randomizer](#seeding-the-randomizer) - [Executing Code Before or After The Attack](#executing-code-before-or-after-the-attack) - [Setting Up a Strategy](#setting-up-a-strategy) - [Stopping The Attack](#stopping-the-attack) - [Customizing The Logger](#customizing-the-logger) - [Cypress](#cypress) - [Playwright](#playwright) - [Docs](#docs) - [Issues](#issues) - [🐛 Bugs](#-bugs) - [💡 Feature Requests](#-feature-requests) - [License](#license) ## 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](http://en.wikipedia.org/wiki/Monkey_test) or [Fuzz testing](http://en.wikipedia.org/wiki/Fuzz_testing), is very common in mobile application development (see for instance the [Android Monkey program](http://developer.android.com/tools/help/monkey.html)). 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](https://www.npmjs.com/) which is bundled with [node](https://nodejs.org/en/) 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](https://marmelab.com/gremlins.js/), 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: ```js 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 ​ gremlin formFiller input pzdoyzshh0k9@o8cpskdb73nmi.r7r in ​ 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: ```js 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: ```js // 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: ```js 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: ```js 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](src/species/clicker.js) clicks anywhere on the visible area of the document - [toucherGremlin](src/species/toucher.js) touches anywhere on the visible area of the document - [formFillerGremlin](src/species/formFiller.js) fills forms by entering data, selecting options, clicking checkboxes, etc - [scrollerGremlin](src/species/scroller.js) scrolls the viewport to reveal another part of the document - [typerGremlin](src/species/typer.js) types keys on the keyboard - [alertMogwai](src/mogwais/alert.js) prevents calls to alert() from blocking the test - [fpsMogwai](src/mogwais/fps.js) logs the number of frames per seconds (FPS) of the browser - [gizmoMogwai](src/mogwais/gizmo.js) 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: ```js 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 : ```js // 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: ```js 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](src/strategies/distribution.js) strategy. You can customize it using the strategies custom object: ```js 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](https://github.com/marmelab/gremlins.js/blob/master/src/index.js#L52). 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](src/strategies/allTogether.js) and [bySpecies](src/strategies/bySpecies.js)), 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: ```js 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: ```js 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. ```js 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](https://github.com/marmelab/gremlins.js/issues?q=is%3aissue+is%3aopen+sort%3areactions-%2b1-desc) label._ ### 🐛 Bugs Please file an issue for bugs, missing documentation, or unexpected behavior. [**See Bugs**](https://github.com/marmelab/gremlins.js/issues?q=is%3aissue+is%3aopen+label%3abug+sort%3acreated-desc) ### 💡 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**](https://github.com/marmelab/gremlins.js/issues?q=is%3aissue+sort%3areactions-%2b1-desc+label%3aenhancement+is%3aopen) ## License gremlins.js is licensed under the [MIT Licence](LICENSE), courtesy of [marmelab](http://marmelab.com). ================================================ FILE: bookmarklet/index.css ================================================ body { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; } .bookmarklet { display: flex; flex-direction: column; align-items: center; justify-content: space-between; } .form { display: flex; justify-content: space-between; margin-bottom: 20px; width: 100%; } .bookmarklet-container { display: flex; flex-direction: column; align-items: center; } .code-container { background-color: antiquewhite; } .code { white-space: pre-wrap; color: darkslategrey; } .code-title { text-align: center; } ================================================ FILE: bookmarklet/index.html ================================================ Gremlins.js Bookmarklet

Species

Mogwais

Strategies

Drag and drop the link below to your bookmarks toolbar

gremlins.js

Bookmarklet Code

================================================ FILE: cypress/fixtures/example.json ================================================ ================================================ FILE: cypress/integration/formFiller.spec.js ================================================ import Chance from 'chance'; import { createHorde, species, strategies } from '../../src/index'; const seed = 'formFiller'; describe('Form filler', () => { let horde; beforeEach(() => { return cy.visit('formFiller.html').then(() => cy.window().then((pageWindow) => { horde = createHorde({ species: [species.formFiller()], strategies: [strategies.bySpecies({ nb: 10 })], window: pageWindow, randomizer: new Chance(seed), }); }) ); }); it('should fill text input with seeded value', () => { return cy.wrap(horde.unleash()).then(() => { cy.get('input[type="text"]').should('have.value', '7uv'); }); }); it('should fill number input with seeded value', () => { return cy.wrap(horde.unleash()).then(() => { cy.get('input[type="number"]').should('have.value', '693'); }); }); it('should fill email input with seeded value', () => { return cy.wrap(horde.unleash()).then(() => { cy.get('input[type="email"]').should('have.value', 'ul@codipo.vn'); }); }); }); ================================================ FILE: cypress/pages/formFiller.html ================================================ ================================================ FILE: cypress/plugins/index.js ================================================ module.exports = function () { // configure plugins here }; ================================================ FILE: cypress/support/commands.js ================================================ // Overwrite cy.visit to visit local html files Cypress.Commands.overwrite('visit', (visit, path, options = {}) => visit(`./cypress/pages/${path}`, options)); ================================================ FILE: cypress/support/index.js ================================================ import './commands'; ================================================ FILE: cypress.json ================================================ { "defaultCommandTimeout": 10000, "video": false } ================================================ FILE: jest.config.js ================================================ module.exports = { roots: ['/src'], resetMocks: true, resetModules: true, }; ================================================ FILE: package.json ================================================ { "name": "gremlins.js", "version": "2.2.0", "description": "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.", "main": "dist/gremlins.min.js", "files": [ "dist" ], "scripts": { "start": "rollup -c -w", "build": "cross-env NODE_ENV=production rollup -c", "test": "cross-env NODE_ENV=test jest", "test:watch": "cross-env NODE_ENV=test jest --watch", "lint": "eslint .", "format": "prettier --write --check \"**/*.+(js|json|md)\"", "serve": "serve dist", "clear": "rimraf dist", "release": "standard-version", "deploy-gh-pages": "gh-pages --dist bookmarklet", "doctoc": "doctoc README.md", "cypress:open": "cypress open", "cypress:run": "cypress run" }, "repository": { "type": "git", "url": "https://github.com/marmelab/gremlins.js" }, "keywords": [ "monkey", "test", "testing", "stress", "gremlin" ], "author": "Francois Zaninotto", "license": "MIT", "bugs": { "url": "https://github.com/marmelab/gremlins.js/issues" }, "homepage": "https://github.com/marmelab/gremlins.js", "devDependencies": { "@babel/core": "^7.9.0", "@babel/preset-env": "^7.9.5", "@commitlint/cli": "^8.3.5", "@commitlint/config-conventional": "^8.3.4", "@rollup/plugin-commonjs": "^11.0.2", "@rollup/plugin-node-resolve": "^7.1.1", "babel-eslint": "^10.1.0", "babel-jest": "^25.3.0", "cross-env": "^7.0.2", "cypress": "^4.10.0", "doctoc": "^1.4.0", "eslint": "^6.8.0", "eslint-config-prettier": "^6.10.1", "eslint-plugin-babel": "^5.3.0", "eslint-plugin-cypress": "^2.11.1", "eslint-plugin-import": "^2.20.2", "eslint-plugin-jest": "^23.8.2", "eslint-plugin-prettier": "^3.1.2", "gh-pages": "^2.2.0", "husky": "^4.2.3", "jest": "^25.3.0", "lint-staged": "^10.1.2", "prettier": "^2.0.4", "rimraf": "^3.0.2", "rollup": "^2.3.4", "rollup-plugin-babel": "^4.4.0", "rollup-plugin-commonjs": "^10.1.0", "rollup-plugin-terser": "^5.3.0", "serve": "^11.3.0", "standard-version": "^8.0.2" }, "dependencies": { "chance": "^1.1.4", "core-js": "^3.6.4" }, "husky": { "hooks": { "pre-commit": "lint-staged", "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" } }, "lint-staged": { "*.js": "eslint", "*.{js,json,md}": "prettier --write", "README.md": "npm run doctoc" }, "commitlint": { "extends": [ "@commitlint/config-conventional" ] } } ================================================ FILE: rollup.config.js ================================================ import commonjs from '@rollup/plugin-commonjs'; import babel from 'rollup-plugin-babel'; import { terser } from 'rollup-plugin-terser'; import resolve from '@rollup/plugin-node-resolve'; import pkg from './package.json'; const isProduction = process.env.NODE_ENV === 'production'; const umd = [ { input: 'src/index.js', output: { name: 'gremlins', file: pkg.main, format: 'umd', sourcemap: isProduction, }, plugins: [ resolve(), commonjs(), babel({ exclude: /node_modules/, sourceMaps: isProduction, }), isProduction && terser(), ], }, ]; export default umd; ================================================ FILE: src/index.js ================================================ import Chance from 'chance'; import clicker from './species/clicker'; import toucher from './species/toucher'; import formFiller from './species/formFiller'; import scroller from './species/scroller'; import typer from './species/typer'; import alert from './mogwais/alert'; import fps from './mogwais/fps'; import gizmo from './mogwais/gizmo'; import distribution from './strategies/distribution'; import bySpecies from './strategies/bySpecies'; import allTogether from './strategies/allTogether'; import executeInSeries from './utils/executeInSeries'; const defaultConfig = { species: [clicker(), formFiller(), toucher(), scroller(), typer()], mogwais: [fps(), alert(), gizmo()], strategies: [distribution()], logger: console, randomizer: new Chance(), window: window, }; export const createHorde = (userConfig) => { const config = { ...defaultConfig, ...userConfig }; const { logger, randomizer, window } = config; const speciesConfig = { logger, randomizer, window, }; const species = config.species.map((specie) => specie(speciesConfig)); const strategies = config.strategies.map((strat) => strat(randomizer)); const stop = () => strategies.forEach((strat) => strat.stop()); const mogwaisConfig = { ...speciesConfig, stop, }; const mogwais = config.mogwais.map((mogwai) => mogwai(mogwaisConfig)); const unleash = async () => { const beforeHorde = [...mogwais]; const cleansUps = mogwais.map((mogwai) => mogwai.cleanUp).filter((cleanUp) => typeof cleanUp === 'function'); await executeInSeries(beforeHorde, []); const unleashedStrategies = strategies.map((strat) => strat(species)); await Promise.all(unleashedStrategies); await executeInSeries(cleansUps, []); }; return { unleash, stop, }; }; export const species = { clicker, toucher, formFiller, scroller, typer }; export const allSpecies = Object.values(species).map((specie) => specie()); export const mogwais = { alert, fps, gizmo }; export const allMogwais = Object.values(mogwais).map((mogwai) => mogwai()); export const strategies = { distribution, bySpecies, allTogether }; export { default as Chance } from 'chance'; ================================================ FILE: src/mogwais/alert.js ================================================ const getDefaultConfig = (randomizer) => { const defaultWatchEvents = ['alert', 'confirm', 'prompt']; const defaultConfirmResponse = () => { return randomizer.bool(); }; const defaultPromptResponse = () => { return randomizer.sentence(); }; return { watchEvents: defaultWatchEvents, confirmResponse: defaultConfirmResponse, promptResponse: defaultPromptResponse, }; }; export default (userConfig) => ({ logger, randomizer, window }) => { const config = { ...getDefaultConfig(randomizer), ...userConfig }; const alert = window.alert; const confirm = window.confirm; const prompt = window.prompt; const alertMogwai = () => { if (!logger) { return; } if (config.watchEvents.includes('alert')) { window.alert = (msg) => { logger.warn('mogwai ', 'alert ', msg, 'alert'); }; } if (config.watchEvents.includes('confirm')) { window.confirm = (msg) => { config.confirmResponse(); logger.warn('mogwai ', 'alert ', msg, 'confirm'); }; } if (config.watchEvents.includes('prompt')) { window.prompt = (msg) => { config.promptResponse(); logger.warn('mogwai ', 'alert ', msg, 'prompt'); }; } }; alertMogwai.cleanUp = () => { window.alert = alert; window.confirm = confirm; window.prompt = prompt; return alertMogwai; }; return alertMogwai; }; ================================================ FILE: src/mogwais/alert.spec.js ================================================ import alert from './alert'; describe('alert', () => { const chanceBoolMock = jest.fn(); const chanceSentenceMock = jest.fn(); let config; let consoleMock; let chanceMock; beforeEach(() => { consoleMock = { warn: jest.fn() }; chanceMock = { bool: chanceBoolMock, sentence: chanceSentenceMock, }; config = { logger: consoleMock, randomizer: chanceMock, window, }; }); it('should call logger warn when window.alert is call', () => { const mogwais = alert()(config); mogwais(); window.alert('new alert'); expect(consoleMock.warn).toHaveBeenCalledTimes(1); expect(consoleMock.warn).toHaveBeenCalledWith('mogwai ', 'alert ', 'new alert', 'alert'); }); it('should call logger warn when window.confirm is call', () => { const mogwais = alert()(config); mogwais(); window.confirm('new confirm'); expect(consoleMock.warn).toHaveBeenCalledTimes(1); expect(consoleMock.warn).toHaveBeenCalledWith('mogwai ', 'alert ', 'new confirm', 'confirm'); }); it('should call logger warn when window.prompt is call', () => { const mogwais = alert()(config); mogwais(); window.prompt('new prompt'); expect(consoleMock.warn).toHaveBeenCalledTimes(1); expect(consoleMock.warn).toHaveBeenCalledWith('mogwai ', 'alert ', 'new prompt', 'prompt'); }); it('should call randomize bool when window.confirm is call', () => { const mogwais = alert()(config); mogwais(); window.confirm('new confirm'); expect(chanceBoolMock).toHaveBeenCalledTimes(1); }); it('should call randomize sentence when window.prompt is call', () => { const mogwais = alert()(config); mogwais(); window.prompt('new prompt'); expect(chanceSentenceMock).toHaveBeenCalledTimes(1); }); it('should cleanup the window prop when cleanUp function is call', () => { jest.spyOn(window, 'alert').mockImplementation(); const mogwais = alert()(config); mogwais(); window.alert('new alert'); expect(consoleMock.warn).toHaveBeenCalledTimes(1); mogwais.cleanUp(); window.alert('new alert'); expect(consoleMock.warn).toHaveBeenCalledTimes(1); }); it('should not override the window object when logger is not defined ', () => { const mogwais = alert()(config); mogwais(); window.alert('new alert'); expect(chanceSentenceMock).toHaveBeenCalledTimes(0); }); }); ================================================ FILE: src/mogwais/fps.js ================================================ const NEXT_FRAME_MS = 16; const getDefaultConfig = () => { const defaultLevelSelector = (fps) => { if (fps < 10) return 'error'; if (fps < 20) return 'warn'; return 'log'; }; return { delay: 500, // how often should the fps be measured levelSelector: defaultLevelSelector, }; }; export default (userConfig) => ({ logger, window }) => { const config = { ...getDefaultConfig(), ...userConfig }; let initialTime = -Infinity; // force initial measure let enabled; const loop = (time) => { if (time - initialTime > config.delay) { measureFPS(time); initialTime = time; } if (!enabled) return; window.requestAnimationFrame(loop); }; const measureFPS = () => { let lastTime; const init = (time) => { lastTime = time; window.requestAnimationFrame(measure); }; const measure = (time) => { const fps = time - lastTime < NEXT_FRAME_MS ? 60 : 1000 / (time - lastTime); const level = config.levelSelector(fps); if (logger) { logger[level]('mogwai ', 'fps ', fps); } }; window.requestAnimationFrame(init); }; const fpsMogwai = () => { enabled = true; window.requestAnimationFrame(loop); }; fpsMogwai.cleanUp = () => { enabled = false; return fpsMogwai; }; return fpsMogwai; }; ================================================ FILE: src/mogwais/fps.spec.js ================================================ import fps from './fps'; describe('fps', () => { let consoleMock; let config; let time; beforeEach(() => { consoleMock = { warn: jest.fn() }; time = 0; jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => { time += 100; if (time < 1000) { return cb(time); } }); config = { logger: consoleMock, window, }; }); it('should log two times the fps mogwais', async () => { const mogwais = fps()(config); mogwais(); mogwais.cleanUp(); expect(consoleMock.warn).toHaveBeenCalledTimes(2); expect(consoleMock.warn).toHaveBeenNthCalledWith(1, 'mogwai ', 'fps ', 10); expect(consoleMock.warn).toHaveBeenNthCalledWith(2, 'mogwai ', 'fps ', 10); }); }); ================================================ FILE: src/mogwais/gizmo.js ================================================ const defaultConfig = { maxErrors: 10 }; export default (userConfig) => ({ logger, stop, window }) => { const config = { ...defaultConfig, ...userConfig }; let realOnError; let realLoggerError; const gizmoMogwai = () => { let nbErrors = 0; const incrementNbErrors = () => { nbErrors++; if (nbErrors === config.maxErrors) { stop(); if (!logger) return; window.setTimeout(() => { logger.warn('mogwai ', 'gizmo ', 'stopped test execution after ', config.maxErrors, 'errors'); }, 4); } }; realOnError = window.onerror; window.onerror = (...args) => { incrementNbErrors(); return realOnError ? realOnError(...args) : false; }; realLoggerError = console.error; console.error = (...args) => { incrementNbErrors(); realLoggerError(...args); }; }; gizmoMogwai.cleanUp = () => { window.onerror = realOnError; console.error = realLoggerError.bind(console); return gizmoMogwai; }; return gizmoMogwai; }; ================================================ FILE: src/mogwais/gizmo.spec.js ================================================ import gizmo from './gizmo'; jest.useFakeTimers(); describe('gizmo', () => { let config; let stopMock; let consoleErrorSpy; let windowErrorSpy = jest.fn(); beforeEach(() => { stopMock = jest.fn(); consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); window.onerror = windowErrorSpy; config = { logger: console, stop: stopMock, window, }; }); it('should call console.error with right args', () => { const mogwais = gizmo()(config); mogwais(); console.error('first error'); expect(consoleErrorSpy).toHaveBeenCalledTimes(1); expect(consoleErrorSpy).toHaveBeenCalledWith('first error'); }); it('should call window.error with right args', () => { const mogwais = gizmo()(config); mogwais(); window.onerror('first error', 'https://foo.bar', 10); expect(windowErrorSpy).toHaveBeenCalledTimes(1); expect(windowErrorSpy).toHaveBeenCalledWith('first error', 'https://foo.bar', 10); }); it('should call stop when maxErrors is reached', () => { const mogwais = gizmo({ maxErrors: 2 })(config); mogwais(); console.error('first error'); console.error('second', 'error'); expect(consoleErrorSpy).toHaveBeenCalledTimes(2); expect(consoleErrorSpy).toHaveBeenNthCalledWith(1, 'first error'); expect(consoleErrorSpy).toHaveBeenNthCalledWith(2, 'second', 'error'); expect(stopMock).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 4); }); }); ================================================ FILE: src/species/clicker.js ================================================ const getDefaultConfig = (randomizer, window) => { const document = window.document; const body = document.body; const defaultClickTypes = [ 'click', 'click', 'click', 'click', 'click', 'click', 'dblclick', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseover', 'mouseover', 'mousemove', 'mouseout', ]; const defaultPositionSelector = () => { return [ randomizer.natural({ max: Math.max(0, document.documentElement.clientWidth - 1), }), randomizer.natural({ max: Math.max(0, document.documentElement.clientHeight - 1), }), ]; }; const defaultShowAction = (x, y) => { const clickSignal = document.createElement('div'); clickSignal.style.zIndex = 2000; clickSignal.style.border = '3px solid red'; // todo clean chrome/mozilla hack clickSignal.style['border-radius'] = '50%'; // Chrome clickSignal.style.borderRadius = '50%'; // Mozilla clickSignal.style.width = '40px'; clickSignal.style.height = '40px'; clickSignal.style['box-sizing'] = 'border-box'; clickSignal.style.position = 'absolute'; clickSignal.style.webkitTransition = 'opacity 1s ease-out'; clickSignal.style.mozTransition = 'opacity 1s ease-out'; clickSignal.style.transition = 'opacity 1s ease-out'; clickSignal.style.left = x - 20 + 'px'; clickSignal.style.top = y - 20 + 'px'; const element = body.appendChild(clickSignal); setTimeout(() => { body.removeChild(element); }, 1000); setTimeout(() => { element.style.opacity = 0; }, 50); }; const defaultCanClick = () => { return true; }; return { clickTypes: defaultClickTypes, positionSelector: defaultPositionSelector, showAction: defaultShowAction, canClick: defaultCanClick, maxNbTries: 10, log: false, }; }; export default (userConfig) => ({ logger, randomizer, window }) => { const document = window.document; const config = { ...getDefaultConfig(randomizer, window), ...userConfig, }; return () => { let position; let posX; let posY; let targetElement; let nbTries = 0; do { position = config.positionSelector(); posX = position[0]; posY = position[1]; targetElement = document.elementFromPoint(posX, posY); nbTries++; if (nbTries > config.maxNbTries) return; } while (!targetElement || !config.canClick(targetElement)); const evt = document.createEvent('MouseEvents'); const clickType = randomizer.pick(config.clickTypes); // todo remove deprecated https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent evt.initMouseEvent(clickType, true, true, window, 0, 0, 0, posX, posY, false, false, false, false, 0, null); targetElement.dispatchEvent(evt); if (typeof config.showAction === 'function') { config.showAction(posX, posY, clickType); } if (logger && config.log) { logger.log('gremlin', 'clicker ', clickType, 'at', posX, posY); } }; }; ================================================ FILE: src/species/clicker.spec.js ================================================ import clicker from './clicker'; jest.useFakeTimers(); describe('clicker', () => { const dispatchEventSpy = jest.fn(); const initMouseEventSpy = jest.fn(); let config; let consoleMock; let chanceMock; beforeEach(() => { consoleMock = { log: jest.fn() }; chanceMock = { natural: ({ max }) => max, pick: (types) => types[0], // return click types }; document.body.innerHTML = '
my div
'; // can't be delete in afterEach... if (document.elementFromPoint === undefined) { Object.defineProperty(document, 'elementFromPoint', { get: () => () => ({ ...document.getElementById('myid'), dispatchEvent: dispatchEventSpy, }), }); } Object.defineProperty(document.documentElement, 'clientWidth', { value: 11, }); Object.defineProperty(document.documentElement, 'clientHeight', { value: 11, }); jest.spyOn(document, 'createEvent').mockImplementation(() => ({ initMouseEvent: initMouseEventSpy })); config = { logger: consoleMock, randomizer: chanceMock, window, }; }); it('should log the cliker', () => { const species = clicker({ log: true })(config); species(); expect(consoleMock.log).toHaveBeenCalledTimes(1); expect(consoleMock.log).toHaveBeenCalledWith('gremlin', 'clicker ', 'click', 'at', 10, 10); }); it("should click on element but don't show element", () => { const species = clicker({ showAction: false })(config); species(); expect(dispatchEventSpy).toHaveBeenCalledTimes(1); expect(document.getElementsByTagName('div')).toHaveLength(1); }); it("should try to click twice on element but can't click at the end", () => { const canClickSpy = jest.fn(); const species = clicker({ canClick: canClickSpy, maxNbTries: 2 })(config); species(); expect(canClickSpy).toHaveBeenCalledTimes(2); expect(dispatchEventSpy).toHaveBeenCalledTimes(0); }); it('should click on myid element and add new element', () => { const species = clicker()(config); species(); // Click on myid element expect(initMouseEventSpy).toHaveBeenCalledWith( 'click', true, true, window, 0, 0, 0, 10, 10, false, false, false, false, 0, null ); expect(dispatchEventSpy).toHaveBeenCalledTimes(1); // Add div element expect(document.getElementsByTagName('div')).toHaveLength(2); expect(setTimeout).toHaveBeenCalledTimes(2); expect(setTimeout).toHaveBeenNthCalledWith(1, expect.any(Function), 1000); expect(setTimeout).toHaveBeenNthCalledWith(2, expect.any(Function), 50); }); }); ================================================ FILE: src/species/formFiller.js ================================================ const getDefaultConfig = (randomizer, window) => { const document = window.document; /** * Hacky function to trigger react, angular & vue.js onChange on input */ const triggerSimulatedOnChange = (element, newValue, prototype) => { const lastValue = element.value; element.value = newValue; const nativeInputValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set; nativeInputValueSetter.call(element, newValue); const event = new Event('input', { bubbles: true }); // React 15 event.simulated = true; // React >= 16 let tracker = element._valueTracker; if (tracker) { tracker.setValue(lastValue); } element.dispatchEvent(event); }; const fillTextElement = (element) => { const character = randomizer.character(); const newValue = element.value + character; triggerSimulatedOnChange(element, newValue, window.HTMLInputElement.prototype); return character; }; const fillTextAreaElement = (element) => { const character = randomizer.character(); const newValue = element.value + character; triggerSimulatedOnChange(element, newValue, window.HTMLTextAreaElement.prototype); return character; }; const fillNumberElement = (element) => { const number = randomizer.character({ pool: '0123456789' }); const newValue = element.value + number; triggerSimulatedOnChange(element, newValue, window.HTMLInputElement.prototype); return number; }; const fillSelect = (element) => { const options = element.querySelectorAll('option'); if (options.length === 0) return; const randomOption = randomizer.pick(options); options.forEach((option) => { option.selected = option.value === randomOption.value; }); return randomOption.value; }; const fillRadio = (element) => { // using mouse events to trigger listeners const evt = document.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); element.dispatchEvent(evt); return element.value; }; const fillCheckbox = (element) => { // using mouse events to trigger listeners const evt = document.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); element.dispatchEvent(evt); return element.value; }; const fillEmail = (element) => { const email = randomizer.email(); triggerSimulatedOnChange(element, email, window.HTMLInputElement.prototype); return email; }; const defaultMapElements = { textarea: fillTextAreaElement, 'input[type="text"]': fillTextElement, 'input[type="password"]': fillTextElement, 'input[type="number"]': fillNumberElement, select: fillSelect, 'input[type="radio"]': fillRadio, 'input[type="checkbox"]': fillCheckbox, 'input[type="email"]': fillEmail, 'input:not([type])': fillTextElement, }; const defaultShowAction = (element) => { if (typeof element.attributes['data-old-border'] === 'undefined') { element.attributes['data-old-border'] = element.style.border; } const oldBorder = element.attributes['data-old-border']; element.style.border = '1px solid red'; setTimeout(() => { element.style.border = oldBorder; }, 500); }; const defaultCanFillElement = () => { return true; }; return { elementMapTypes: defaultMapElements, showAction: defaultShowAction, canFillElement: defaultCanFillElement, maxNbTries: 10, log: false, }; }; export default (userConfig) => ({ logger, randomizer, window }) => { const document = window.document; const config = { ...getDefaultConfig(randomizer, window), ...userConfig }; return () => { // Retrieve all selectors const elementTypes = Object.keys(config.elementMapTypes); let element; let nbTries = 0; do { // Find a random element within all selectors const elements = document.querySelectorAll(elementTypes.join(',')); if (elements.length === 0) return; element = randomizer.pick(elements); nbTries++; if (nbTries > config.maxNbTries) return; } while (!element || !config.canFillElement(element)); // Retrieve element type const elementType = Object.keys(config.elementMapTypes).find((selector) => element.matches(selector)); const value = config.elementMapTypes[elementType](element); if (typeof config.showAction === 'function') { config.showAction(element); } if (logger && config.log) { logger.log('gremlin', 'formFiller', 'input', value, 'in', element); } }; }; ================================================ FILE: src/species/formFiller.spec.js ================================================ import formFiller from './formFiller'; jest.useFakeTimers(); describe('formFiller', () => { let consoleMock; let inputText; let chanceMock; let config; beforeEach(() => { consoleMock = { log: jest.fn() }; chanceMock = { character: () => 1, email: () => 'cofveve@cofveve.com', pick: (types) => types[0], // return click types }; inputText = document.createElement('input'); inputText.setAttribute('type', 'text'); inputText.setAttribute('id', 'myid'); document.body.appendChild(inputText); config = { logger: consoleMock, randomizer: chanceMock, window, }; }); afterEach(() => { document.body.innerHTML = ''; }); it('should log the formFiller', () => { const species = formFiller({ log: true })(config); species(); expect(consoleMock.log).toHaveBeenCalledTimes(1); expect(consoleMock.log).toHaveBeenCalledWith('gremlin', 'formFiller', 'input', 1, 'in', inputText); }); it("should fill element but don't show element", () => { const species = formFiller({ showAction: false })(config); species(); expect(document.getElementById('myid')).toBe(inputText); expect(inputText.value).toBe('1'); }); it("should try to fill twice on element but can't fill at the end", () => { const canFillElementSpy = jest.fn(); const species = formFiller({ canFillElement: canFillElementSpy, maxNbTries: 2 })(config); species(); expect(canFillElementSpy).toHaveBeenCalledTimes(2); expect(inputText.value).toBe(''); }); it('should fill element and add new element', () => { const species = formFiller()(config); species(); expect(inputText.value).toBe('1'); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 500); }); }); ================================================ FILE: src/species/scroller.js ================================================ const getDefaultConfig = (randomizer, window) => { const document = window.document; const documentElement = document.documentElement; const body = document.body; const defaultPositionSelector = () => { const documentWidth = Math.max( body.scrollWidth, body.offsetWidth, documentElement.scrollWidth, documentElement.offsetWidth, documentElement.clientWidth ); const documentHeight = Math.max( body.scrollHeight, body.offsetHeight, documentElement.scrollHeight, documentElement.offsetHeight, documentElement.clientHeight ); return [ randomizer.natural({ max: documentWidth - documentElement.clientWidth, }), randomizer.natural({ max: documentHeight - documentElement.clientHeight, }), ]; }; const defaultShowAction = (scrollX, scrollY) => { const scrollSignal = document.createElement('div'); scrollSignal.style.zIndex = 2000; scrollSignal.style.border = '3px solid red'; scrollSignal.style.width = documentElement.clientWidth - 25 + 'px'; scrollSignal.style.height = documentElement.clientHeight - 25 + 'px'; scrollSignal.style.position = 'absolute'; scrollSignal.style.webkitTransition = 'opacity 1s ease-out'; scrollSignal.style.mozTransition = 'opacity 1s ease-out'; scrollSignal.style.transition = 'opacity 1s ease-out'; scrollSignal.style.left = scrollX + 10 + 'px'; scrollSignal.style.top = scrollY + 10 + 'px'; scrollSignal.style['pointer-events'] = 'none'; const element = body.appendChild(scrollSignal); setTimeout(() => { body.removeChild(element); }, 1000); setTimeout(() => { element.style.opacity = 0; }, 50); }; return { positionSelector: defaultPositionSelector, showAction: defaultShowAction, log: false, }; }; export default (userConfig) => ({ logger, randomizer, window }) => { const config = { ...getDefaultConfig(randomizer, window), ...userConfig }; return () => { const position = config.positionSelector(); const scrollX = position[0]; const scrollY = position[1]; window.scrollTo(scrollX, scrollY); if (typeof config.showAction === 'function') { config.showAction(scrollX, scrollY); } if (logger && config.log) { logger.log('gremlin', 'scroller ', 'scroll to', scrollX, scrollY); } }; }; ================================================ FILE: src/species/scroller.spec.js ================================================ import scroller from './scroller'; jest.useFakeTimers(); describe('scroller', () => { let consoleMock; let chanceMock; let config; const scrollToSpy = jest.fn(); beforeEach(() => { consoleMock = { log: jest.fn() }; chanceMock = { natural: ({ max }) => max, }; Object.defineProperty(window, 'scrollTo', { value: scrollToSpy, writable: true }); const documentElementProps = { clientWidth: 10, clientHeight: 10, scrollWidth: 15, scrollHeight: 15, }; Object.keys(documentElementProps).forEach((key) => { Object.defineProperty(document.documentElement, key, { value: documentElementProps[key], }); }); config = { logger: consoleMock, randomizer: chanceMock, window, }; }); it('should log the scroller', () => { const species = scroller({ log: true })(config); species(); expect(consoleMock.log).toHaveBeenCalledTimes(1); expect(consoleMock.log).toHaveBeenCalledWith('gremlin', 'scroller ', 'scroll to', 5, 5); }); it("should scroll but don't show element", () => { const species = scroller({ showAction: false })(config); species(); expect(scrollToSpy).toHaveBeenCalledTimes(1); expect(scrollToSpy).toHaveBeenCalledWith(5, 5); expect(document.getElementsByTagName('div')).toHaveLength(1); }); it('should scroll and add new element', () => { const species = scroller()(config); species(); expect(scrollToSpy).toHaveBeenCalledTimes(1); expect(scrollToSpy).toHaveBeenCalledWith(5, 5); expect(document.getElementsByTagName('div')).toHaveLength(2); expect(setTimeout).toHaveBeenCalledTimes(2); expect(setTimeout).toHaveBeenNthCalledWith(1, expect.any(Function), 1000); expect(setTimeout).toHaveBeenNthCalledWith(2, expect.any(Function), 50); }); }); ================================================ FILE: src/species/toucher.js ================================================ const getDefaultConfig = (randomizer, window) => { const document = window.document; const body = document.body; const defaultTouchTypes = [ 'tap', 'tap', 'tap', 'doubletap', 'gesture', 'gesture', 'gesture', 'multitouch', 'multitouch', ]; const defaultPositionSelector = () => { return [ randomizer.natural({ max: Math.max(0, document.documentElement.clientWidth - 1), }), randomizer.natural({ max: Math.max(0, document.documentElement.clientHeight - 1), }), ]; }; const defaultShowAction = (touches) => { const fragment = document.createDocumentFragment(); touches.forEach((touch) => { const touchSignal = document.createElement('div'); touchSignal.style.zIndex = 2000; touchSignal.style.background = 'red'; touchSignal.style['border-radius'] = '50%'; // Chrome touchSignal.style.borderRadius = '50%'; // Mozilla touchSignal.style.width = '20px'; touchSignal.style.height = '20px'; touchSignal.style.position = 'absolute'; touchSignal.style.webkitTransition = 'opacity .5s ease-out'; touchSignal.style.mozTransition = 'opacity .5s ease-out'; touchSignal.style.transition = 'opacity .5s ease-out'; touchSignal.style.left = touch.x - 10 + 'px'; touchSignal.style.top = touch.y - 10 + 'px'; const element = fragment.appendChild(touchSignal); setTimeout(() => { body.removeChild(element); }, 500); setTimeout(() => { element.style.opacity = 0; }, 50); }); document.body.appendChild(fragment); }; const defaultCanTouch = () => { return true; }; return { touchTypes: defaultTouchTypes, positionSelector: defaultPositionSelector, showAction: defaultShowAction, canTouch: defaultCanTouch, maxNbTries: 10, maxTouches: 2, log: false, }; }; export default (userConfig) => ({ logger, randomizer, window }) => { const document = window.document; const config = { ...getDefaultConfig(randomizer, window), ...userConfig }; const getTouches = (center, points, radius, degrees) => { const cx = center[0]; const cy = center[1]; const touches = []; // just one touch, at the center if (points === 1) { return [{ x: cx, y: cy }]; } radius = radius || 100; degrees = degrees !== null ? (degrees * Math.PI) / 180 : 0; const slice = (2 * Math.PI) / points; for (let i = 0; i < points; i++) { let angle = slice * i + degrees; touches.push({ x: cx + radius * Math.cos(angle), y: cy + radius * Math.sin(angle), }); } return touches; }; const triggerTouch = (touches, element, type) => { const touchlist = []; const event = document.createEvent('Event'); event.initEvent('touch' + type, true, true); touches.forEach((touch, i) => { const x = Math.round(touch.x); const y = Math.round(touch.y); touchlist.push({ pageX: x, pageY: y, clientX: x, clientY: y, screenX: x, screenY: y, target: element, identifier: i, }); }); event.touches = type === 'end' ? [] : touchlist; event.targetTouches = type === 'end' ? [] : touchlist; event.changedTouches = touchlist; element.dispatchEvent(event); if (typeof config.showAction === 'function') { config.showAction(touches); } }; const triggerGesture = (element, startPos, startTouches, gesture, done) => { const interval = 10; const loops = Math.ceil(gesture.duration / interval); let loop = 1; const gestureLoop = () => { // calculate the radius let radius = gesture.radius; if (gesture.scale !== 1) { radius = gesture.radius - gesture.radius * (1 - gesture.scale) * ((1 / loops) * loop); } // calculate new position/rotation const posX = startPos[0] + (gesture.distanceX / loops) * loop; const posY = startPos[1] + (gesture.distanceY / loops) * loop; const rotation = typeof gesture.rotation === 'number' ? (gesture.rotation / loops) * loop : null; const touches = getTouches([posX, posY], startTouches.length, radius, rotation); const isFirst = loop === 1; const isLast = loop === loops; if (isFirst) { triggerTouch(touches, element, 'start'); } else if (isLast) { triggerTouch(touches, element, 'end'); return done(touches); } else { triggerTouch(touches, element, 'move'); } setTimeout(gestureLoop, interval); loop++; }; gestureLoop(); }; const touchTypes = { // tap, like a click event, only 1 touch // could also be a slow tap, that could turn out to be a hold tap(position, element, log) { const touches = getTouches(position, 1); const gesture = { duration: randomizer.integer({ min: 20, max: 700 }), }; triggerTouch(touches, element, 'start'); setTimeout(() => { triggerTouch(touches, element, 'end'); log(touches, gesture); }, gesture.duration); }, // doubletap, like a dblclick event, only 1 touch // could also be a slow doubletap, that could turn out to be a hold doubletap(position, element, log) { touchTypes.tap(position, element, () => { setTimeout(() => { touchTypes.tap(position, element, log); }, 30); }); }, // single touch gesture, could be a drag and swipe, with 1 points gesture(position, element, log) { const gesture = { distanceX: randomizer.integer({ min: -100, max: 200 }), distanceY: randomizer.integer({ min: -100, max: 200 }), duration: randomizer.integer({ min: 20, max: 500 }), }; const touches = getTouches(position, 1, gesture.radius); triggerGesture(element, position, touches, gesture, (touches) => { log(touches, gesture); }); }, // multitouch gesture, could be a drag, swipe, pinch and rotate, with 2 or more points multitouch(position, element, log) { const points = randomizer.integer({ min: 2, max: config.maxTouches, }); const gesture = { scale: randomizer.floating({ min: 0, max: 2 }), rotation: randomizer.natural({ min: 0, max: 100 }), radius: randomizer.integer({ min: 50, max: 200 }), distanceX: randomizer.integer({ min: -20, max: 20 }), distanceY: randomizer.integer({ min: -20, max: 20 }), duration: randomizer.integer({ min: 100, max: 1500 }), }; const touches = getTouches(position, points, gesture.radius); triggerGesture(element, position, touches, gesture, (touches) => { log(touches, gesture); }); }, }; return () => { let position; let posX; let posY; let targetElement; let nbTries = 0; do { position = config.positionSelector(); posX = position[0]; posY = position[1]; targetElement = document.elementFromPoint(posX, posY); nbTries++; if (nbTries > config.maxNbTries) return; } while (!targetElement || !config.canTouch(targetElement)); const touchType = randomizer.pick(config.touchTypes); const log = (touches, details) => { if (typeof config.showAction === 'function') { config.showAction(touches); } if (logger && config.log) { logger.log('gremlin', 'toucher', touchType, 'at', posX, posY, details); } }; touchTypes[touchType](position, targetElement, log); }; }; ================================================ FILE: src/species/toucher.spec.js ================================================ import toucher from './toucher'; describe('toucher', () => { const dispatchEventSpy = jest.fn(); const initEventSpy = jest.fn(); let config; let inputText; let chanceMock; let consoleMock; beforeEach(() => { chanceMock = { natural: ({ max }) => max, floating: ({ max }) => max, integer: ({ max }) => max, pick: (types) => types[0], }; consoleMock = { log: jest.fn() }; inputText = document.createElement('input'); inputText.setAttribute('type', 'text'); inputText.setAttribute('id', 'myid'); document.body.appendChild(inputText); // can't be delete in afterEach... if (document.elementFromPoint === undefined) { Object.defineProperty(document, 'elementFromPoint', { get: () => () => ({ ...document.getElementById('myid'), dispatchEvent: dispatchEventSpy, }), }); } Object.defineProperty(document.documentElement, 'clientWidth', { value: 11, }); Object.defineProperty(document.documentElement, 'clientHeight', { value: 11, }); jest.spyOn(document, 'createEvent').mockImplementation(() => ({ initEvent: initEventSpy })); jest.useFakeTimers(); config = { logger: consoleMock, randomizer: chanceMock, window, }; }); afterEach(() => { document.body.innerHTML = ''; }); it('should log the toucher', () => { const species = toucher({ log: true })(config); species(); jest.runAllTimers(); expect(consoleMock.log).toHaveBeenCalledTimes(1); expect(consoleMock.log).toHaveBeenCalledWith('gremlin', 'toucher', 'tap', 'at', 10, 10, { duration: 700 }); }); it("should touch the element but don't show element", () => { const species = toucher({ showAction: false })(config); species(); expect(dispatchEventSpy).toHaveBeenCalledTimes(1); expect(document.getElementsByTagName('div')).toHaveLength(0); }); it('should touch on myid element and add new element', () => { const species = toucher()(config); species(); expect(dispatchEventSpy).toHaveBeenCalledTimes(1); expect(document.getElementsByTagName('div')).toHaveLength(1); expect(setTimeout).toHaveBeenCalledTimes(3); expect(setTimeout).toHaveBeenNthCalledWith(1, expect.any(Function), 500); expect(setTimeout).toHaveBeenNthCalledWith(2, expect.any(Function), 50); expect(setTimeout).toHaveBeenNthCalledWith(3, expect.any(Function), 700); }); }); ================================================ FILE: src/species/typer.js ================================================ const getDefaultConfig = (randomizer, window) => { const document = window.document; const body = document.body; const defaultEventTypes = ['keypress', 'keyup', 'keydown']; const defaultKeyGenerator = () => { return randomizer.natural({ min: 3, max: 254 }); }; const defaultTargetElement = (x, y) => { return document.elementFromPoint(x, y); }; const defaultShowAction = (targetElement, x, y, key) => { const typeSignal = document.createElement('div'); typeSignal.style.zIndex = 2000; typeSignal.style.border = '3px solid orange'; typeSignal.style['border-radius'] = '50%'; // Chrome typeSignal.style.borderRadius = '50%'; // Mozilla typeSignal.style.width = '40px'; typeSignal.style.height = '40px'; typeSignal.style['box-sizing'] = 'border-box'; typeSignal.style.position = 'absolute'; typeSignal.style.webkitTransition = 'opacity 1s ease-out'; typeSignal.style.mozTransition = 'opacity 1s ease-out'; typeSignal.style.transition = 'opacity 1s ease-out'; typeSignal.style.left = x + 'px'; typeSignal.style.top = y + 'px'; typeSignal.style.textAlign = 'center'; typeSignal.style.paddingTop = '7px'; typeSignal.innerHTML = String.fromCharCode(key); const element = body.appendChild(typeSignal); setTimeout(() => { body.removeChild(element); }, 1000); setTimeout(() => { element.style.opacity = 0; }, 50); }; return { eventTypes: defaultEventTypes, showAction: defaultShowAction, keyGenerator: defaultKeyGenerator, targetElement: defaultTargetElement, log: false, }; }; export default (userConfig) => ({ logger, randomizer, window }) => { const document = window.document; const documentElement = document.documentElement; const config = { ...getDefaultConfig(randomizer, window), ...userConfig }; return () => { const keyboardEvent = document.createEventObject ? document.createEventObject() : document.createEvent('Events'); const eventType = randomizer.pick(config.eventTypes); const key = config.keyGenerator(); const posX = randomizer.natural({ max: Math.max(0, documentElement.clientWidth - 1), }); const posY = randomizer.natural({ max: Math.max(0, documentElement.clientHeight - 1), }); const targetElement = config.targetElement(posX, posY); if (keyboardEvent.initEvent) { keyboardEvent.initEvent(eventType, true, true); } keyboardEvent.keyCode = key; keyboardEvent.which = key; keyboardEvent.keyCodeVal = key; if (targetElement.dispatchEvent) { targetElement.dispatchEvent(keyboardEvent); } else { targetElement.fireEvent('on' + eventType, keyboardEvent); } if (typeof config.showAction === 'function') { config.showAction(targetElement, posX, posY, key); } if (config.log && logger) { logger.log('gremlin', 'typer type', String.fromCharCode(key), 'at', posX, posY); } }; }; ================================================ FILE: src/species/typer.spec.js ================================================ import typer from './typer'; jest.useFakeTimers(); describe('typer', () => { const dispatchEventSpy = jest.fn(); const initMouseEventSpy = jest.fn(); let consoleMock; let inputText; let chanceMock; let config; beforeEach(() => { consoleMock = { log: jest.fn() }; chanceMock = { natural: ({ min, max }) => (min ? 65 : max), // 65 = a pick: (types) => types[0], }; inputText = document.createElement('input'); inputText.setAttribute('type', 'text'); inputText.setAttribute('id', 'myid'); document.body.appendChild(inputText); // can't be delete in afterEach... if (document.elementFromPoint === undefined) { Object.defineProperty(document, 'elementFromPoint', { get: () => () => ({ ...document.getElementById('myid'), dispatchEvent: dispatchEventSpy, }), }); } Object.defineProperty(document.documentElement, 'clientWidth', { value: 11, }); Object.defineProperty(document.documentElement, 'clientHeight', { value: 11, }); jest.spyOn(document, 'createEvent').mockImplementation(() => ({ initMouseEvent: initMouseEventSpy })); config = { logger: consoleMock, randomizer: chanceMock, window, }; }); afterEach(() => { document.body.innerHTML = ''; }); it('should log the typer', () => { const species = typer({ log: true })(config); species(); expect(consoleMock.log).toHaveBeenCalledTimes(1); expect(consoleMock.log).toHaveBeenCalledWith('gremlin', 'typer type', 'A', 'at', 10, 10); }); it("should type on element but don't show element", () => { const species = typer({ showAction: false })(config); species(); expect(dispatchEventSpy).toHaveBeenCalledTimes(1); expect(dispatchEventSpy).toHaveBeenCalledWith({ initMouseEvent: initMouseEventSpy, keyCode: 65, which: 65, keyCodeVal: 65, }); expect(document.getElementsByTagName('div')).toHaveLength(0); }); it('should type on myid element and add new element', () => { const species = typer()(config); species(); expect(dispatchEventSpy).toHaveBeenCalledTimes(1); expect(dispatchEventSpy).toHaveBeenCalledWith({ initMouseEvent: initMouseEventSpy, keyCode: 65, which: 65, keyCodeVal: 65, }); expect(document.getElementsByTagName('div')).toHaveLength(1); expect(setTimeout).toHaveBeenCalledTimes(2); expect(setTimeout).toHaveBeenNthCalledWith(1, expect.any(Function), 1000); expect(setTimeout).toHaveBeenNthCalledWith(2, expect.any(Function), 50); }); }); ================================================ FILE: src/strategies/allTogether.js ================================================ import executeInSeries from '../utils/executeInSeries'; import wait from '../utils/wait'; export default (userConfig) => () => { const defaultConfig = { delay: 10, // delay in milliseconds between each wave nb: 100, // number of waves to execute (can be overridden in params) }; const config = { ...defaultConfig, ...userConfig }; let stopped = false; const allTogetherStrategy = async (gremlins) => { const { nb, delay } = config; for (let i = 0; i < nb; i++) { await wait(delay); if (stopped) { return Promise.resolve(); } await executeInSeries(gremlins, []); } return Promise.resolve(); }; allTogetherStrategy.stop = () => { stopped = true; }; return allTogetherStrategy; }; ================================================ FILE: src/strategies/allTogether.spec.js ================================================ import allTogether from './allTogether'; import * as executeInSeries from '../utils/executeInSeries'; import * as wait from '../utils/wait'; jest.useFakeTimers(); describe('allTogether', () => { it('should contains stop function', async () => { const strategies = allTogether({ nb: 2 })(); expect(typeof strategies.stop === 'function').toBe(true); }); it('should call executeInSeries with all gremlins', async () => { const executeInSeriesSpy = jest.spyOn(executeInSeries, 'default').mockImplementation(); const waitSpy = jest.spyOn(wait, 'default').mockImplementation(); const gremlins = [{ name: 'firstGremlins' }, { name: 'secondGremlins' }]; const strategies = allTogether({ nb: 2 })(); await expect(strategies(gremlins)).resolves.toBe(); expect(waitSpy).toHaveBeenCalledTimes(2); expect(executeInSeriesSpy).toHaveBeenCalledTimes(2); expect(executeInSeriesSpy).toHaveBeenNthCalledWith(1, gremlins, []); expect(executeInSeriesSpy).toHaveBeenNthCalledWith(2, gremlins, []); }); it("should don't call executeInSeries twice when strategies is stop", async () => { const executeInSeriesSpy = jest.spyOn(executeInSeries, 'default').mockImplementation(); const waitSpy = jest.spyOn(wait, 'default').mockImplementation(); const gremlins = [{ name: 'firstGremlins' }]; const strategies = allTogether({ nb: 2 })(); strategies.stop(); await expect(strategies(gremlins)).resolves.toBe(); expect(waitSpy).toHaveBeenCalledTimes(1); expect(executeInSeriesSpy).toHaveBeenCalledTimes(0); }); }); ================================================ FILE: src/strategies/bySpecies.js ================================================ import executeInSeries from '../utils/executeInSeries'; import wait from '../utils/wait'; export default (userConfig) => () => { const defaultConfig = { delay: 10, // delay in milliseconds between each wave nb: 100, // number of waves to execute (can be overridden in params) }; const config = { ...defaultConfig, ...userConfig }; let stopped = false; const bySpeciesStrategy = async (newGremlins) => { const { nb, delay } = config; const gremlins = [...newGremlins]; // clone the array to avoid modifying the original for (let gremlinIndex in gremlins) { const gremlin = gremlins[gremlinIndex]; for (let i = 0; i < nb; i++) { await wait(delay); if (stopped) { return Promise.resolve(); } await executeInSeries([gremlin], []); } } return Promise.resolve(); }; bySpeciesStrategy.stop = () => { stopped = true; }; return bySpeciesStrategy; }; ================================================ FILE: src/strategies/bySpecies.spec.js ================================================ import bySpecies from './bySpecies'; import * as executeInSeries from '../utils/executeInSeries'; import * as wait from '../utils/wait'; jest.useFakeTimers(); describe('bySpecies', () => { beforeEach(() => {}); it('should contains stop function', async () => { const strategies = bySpecies({ nb: 2 })(); expect(typeof strategies.stop === 'function').toBe(true); }); it('should call executeInSeries by species', async () => { const executeInSeriesSpy = jest.spyOn(executeInSeries, 'default').mockImplementation(); const waitSpy = jest.spyOn(wait, 'default').mockImplementation(); const gremlins = [{ name: 'firstGremlins' }, { name: 'secondGremlins' }]; const strategies = bySpecies({ nb: 2 })(); await expect(strategies(gremlins)).resolves.toBe(); expect(waitSpy).toHaveBeenCalledTimes(4); expect(executeInSeriesSpy).toHaveBeenCalledTimes(4); expect(executeInSeriesSpy).toHaveBeenNthCalledWith(1, [{ name: 'firstGremlins' }], []); expect(executeInSeriesSpy).toHaveBeenNthCalledWith(2, [{ name: 'firstGremlins' }], []); expect(executeInSeriesSpy).toHaveBeenNthCalledWith(3, [{ name: 'secondGremlins' }], []); expect(executeInSeriesSpy).toHaveBeenNthCalledWith(4, [{ name: 'secondGremlins' }], []); }); }); ================================================ FILE: src/strategies/distribution.js ================================================ import executeInSeries from '../utils/executeInSeries'; import wait from '../utils/wait'; export default (userConfig) => (randomizer) => { const defaultConfig = { distribution: [], // percentage of each gremlin species ; the sum of all values should equal to 1 delay: 10, nb: 1000, }; const config = { ...defaultConfig, ...userConfig }; let stopped = false; const distributionStrategy = async (newGremlins) => { const { nb, delay } = config; const gremlins = [...newGremlins]; // clone the array to avoid modifying the original const distribution = config.distribution.length === 0 ? getUniformDistribution(gremlins) : config.distribution; if (nb === 0) return Promise.resolve(); for (let i = 0; i < nb; i++) { const gremlin = pickGremlin(gremlins, distribution); await wait(delay); if (stopped) { return Promise.resolve(); } await executeInSeries([gremlin], []); } return Promise.resolve(); }; const getUniformDistribution = (newGremlins) => { const len = newGremlins.length; if (len === 0) return []; const distribution = []; const value = 1 / len; for (let i = 0; i < len; i++) { distribution.push(value); } return distribution; }; const pickGremlin = (newGremlins, distribution) => { let chance = 0; const random = randomizer.floating({ min: 0, max: 1 }); for (let i = 0, count = newGremlins.length; i < count; i++) { chance += distribution[i]; if (random <= chance) return newGremlins[i]; } // no gremlin - probably error in the distribution return () => {}; }; distributionStrategy.stop = () => { stopped = true; }; return distributionStrategy; }; ================================================ FILE: src/strategies/distribution.spec.js ================================================ import distribution from './distribution'; describe('distribution', () => { beforeEach(() => {}); it('should contains stop function', async () => { const strategies = distribution({ nb: 2 })(); expect(typeof strategies.stop === 'function').toBe(true); }); }); ================================================ FILE: src/utils/executeInSeries.js ================================================ /** * Execute a list of functions one after the other. * * Functions can be asynchronous or asynchronous, they will always be * executed in the order of the list. * * @param {Function[]} callbacks - The functions to execute * @param {Array} args - The arguments passed to each function */ export default (callables, args) => callables.reduce((promise, cb) => promise.then(() => cb(...args)), Promise.resolve()); ================================================ FILE: src/utils/executeInSeries.spec.js ================================================ import executeInSeries from './executeInSeries'; describe('executeInSeries', () => { it('should call all callables with correct arguments', async () => { const promise = jest.fn(() => new Promise((resolve) => resolve())); const callable = jest.fn(() => {}); const callables = [promise, callable]; const args = [1, 2]; await executeInSeries(callables, args); expect(promise).toHaveBeenCalledTimes(1); expect(promise).toHaveBeenLastCalledWith(...args); expect(callable).toHaveBeenCalledTimes(1); expect(callable).toHaveBeenLastCalledWith(...args); }); it('should throw an error and stop executing if an error occur', async () => { const promise = jest.fn(() => new Promise((resolve) => resolve())); const rejectPromise = jest.fn(() => new Promise((_, reject) => reject('test reject'))); const callables = [promise, rejectPromise, promise]; const args = [1, 2]; await expect(executeInSeries(callables, args)).rejects.toEqual('test reject'); expect(promise).toHaveBeenCalledTimes(1); expect(promise).toHaveBeenLastCalledWith(...args); expect(rejectPromise).toHaveBeenCalledTimes(1); expect(rejectPromise).toHaveBeenLastCalledWith(...args); }); }); ================================================ FILE: src/utils/wait.js ================================================ export default (time) => new Promise((resolve) => setTimeout(resolve, time)); ================================================ FILE: src/utils/wait.spec.js ================================================ import wait from './wait'; jest.useFakeTimers(); describe('wait', () => { it('should call setTimeout and wait x ms', () => { wait(1000); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000); }); });