From aa42fa13980175a0f84aeddb4e702aedeacaa5f0 Mon Sep 17 00:00:00 2001 From: Jason Palmer Date: Mon, 16 Jan 2017 20:49:43 -0500 Subject: [PATCH] Initial commit --- .gitignore | 2 ++ README.md | 37 +++++++++++++++++++++++++++++++++++++ index.js | 7 +++++++ package.json | 11 +++++++++++ 4 files changed, 57 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 index.js create mode 100644 package.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a8669b1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +yarn.lock +node_modules diff --git a/README.md b/README.md new file mode 100644 index 0000000..ccf3676 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# Jest-Offline + +Jest-Offline is an addon to your Jest test suite which will fail tests that make network requests. + +To install: + +``` +yarn add jest-offline +``` + +To use: + +```javascript +{ + "jest": { + "setupFiles": [ + "/node_modules/jest-offline" + ] + } +} +``` + +Any tests that make network requests will fail with a thrown exception. + +## Why do this? + +Fundamentally, unit tests should not make network requests. Unit tests should be as small as possible and test components in isolation whenever possible. + +Any tests that rely on the network are inherently flaky and can put a strain on systems. + +The best unit tests are tests that give the exact same result every single time you run the test. If they rely on network then that is simply impossible to achieve. + +So jest-offline offers a simple way to: +1. Identify what tests are hitting the network +2. Prevent tests from hitting the network + +You could either use this locally in order to see what tests are hitting the network. Or you could enable this by default on CI so no new tests can be added that hit the network. diff --git a/index.js b/index.js new file mode 100644 index 0000000..314f0c1 --- /dev/null +++ b/index.js @@ -0,0 +1,7 @@ +const Mitm = require('mitm'); +const mitm = Mitm(); + +mitm.on('request', (req, res) => { + throw new Error('Network requests forbidden in offline mode'); + res.end(); +}); diff --git a/package.json b/package.json new file mode 100644 index 0000000..93d3c1e --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "jest-offline", + "version": "1.0.0", + "description": "Add to setupFiles in jest to block network access for tests", + "main": "index.js", + "author": "Jason Palmer", + "license": "Apache 2.0", + "dependencies": { + "mitm": "^1.3.2" + } +}