• Stars
    star
    170
  • Rank 223,357 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

superagent plugin allowing to simulate HTTP calls by returning data fixtures based on the requested URL

npm npm bundle size npm GitHub last commit NPM NPM Downloads Continous Integration

Installation | Usage | Supported Methods | Credits | License

superagent-mock

superagent plugin allowing to simulate HTTP calls by returning data fixtures based on the requested URL.

See this post to know why we use superagent-mock at Bedrock Streaming.

Installation

Install with npm: npm install superagent-mock

Install with yarn: yarn add superagent-mock

Requirements

node >= 8.0 superagent >= ^3.6.0

Usage

First, you have to define the URLs to mock in a configuration file:

// ./superagent-mock-config.js file
module.exports = [
  {
    /**
     * regular expression of URL
     */
    pattern: 'https://domain.example(.*)',

    /**
     * returns the data
     *
     * @param match array Result of the resolution of the regular expression
     * @param params object sent by 'send' function
     * @param headers object set by 'set' function
     * @param context object the context of running the fixtures function
     */
    fixtures: function (match, params, headers, context) {
      /**
       * Returning error codes example:
       *   request.get('https://domain.example/404').end(function(err, res){
       *     console.log(err); // 404
       *     console.log(res.notFound); // true
       *   })
       */
      if (match[1] === '/404') {
        throw new Error(404);
      }

      /**
       * Checking on parameters example:
       *   request.get('https://domain.example/hero').send({superhero: "superman"}).end(function(err, res){
       *     console.log(res.body); // "Your hero: superman"
       *   })
       */

      if (match[1] === '/hero') {
        if(params['superhero']) {
          return 'Your hero:' + params['superhero'];
        } else {
          return 'You didnt choose a hero';
        }
      }


      /**
       * Checking on headers example:
       *   request.get('https://domain.example/authorized_endpoint').set({Authorization: "9382hfih1834h"}).end(function(err, res){
       *     console.log(res.body); // "Authenticated!"
       *   })
       */

      if (match[1] === '/authorized_endpoint') {
        if(headers['Authorization']) {
          return 'Authenticated!';
        } else {
          throw new Error(401); // Unauthorized
        }
      }

      /**
       * Cancelling the mocking for a specific matched route example:
       *   request.get('https://domain.example/server_test').end(function(err, res){
       *     console.log(res.body); // (whatever the actual server would have returned)
       *   })
       */

      if (match[1] === '/server_test') {
        context.cancel = true; // This will cancel the mock process and continue as usual (unmocked)
        return null;
      }

      /**
       * Delaying the response with a specific number of milliseconds:
       *   request.get('https://domain.example/delay_test').end(function(err, res){
       *     console.log(res.body); // This log will be written after the delay time has passed 
       *   })
       */

      if (match[1] === '/delay_test') {
        context.delay = 3000; // This will delay the response by 3 seconds
        return 'zzZ';
      }

      /**
       * Mocking progress events:
       *   request.get('https://domain.example/progress_test')
       *     .on('progress', function (e) { console.log(e.percent + '%'); })
       *     .end(function(err, res){
       *       console.log(res.body); // This log will be written after all progress events emitted 
       *     })
       */

      if (match[1] === '/progress_test') {
        context.progress = {
          parts: 3,               // The number of progress events to emit one after the other with linear progress
                                  //   (Meaning, loaded will be [total/parts])
          delay: 1000,            // [optional] The delay of emitting each of the progress events by ms 
                                  //   (default is 0 unless context.delay specified, then it's [delay/parts])
          total: 100,             // [optional] The total as it will appear in the progress event (default is 100)
          lengthComputable: true, // [optional] The same as it will appear in the progress event (default is true)
          direction: 'upload'     // [optional] superagent adds 'download'/'upload' direction to the event (default is 'upload')
        };
        return 'Hundred percent!';
      }
    },

    /**
     * returns the result of the GET request
     *
     * @param match array Result of the resolution of the regular expression
     * @param data  mixed Data returns by `fixtures` attribute
     */
    get: function (match, data) {
      return {
        body: data
      };
    },

    /**
     * returns the result of the POST request
     *
     * @param match array Result of the resolution of the regular expression
     * @param data  mixed Data returns by `fixtures` attribute
     */
    post: function (match, data) {
      return {
        status: 201
      };
    }
  },
  ...
];

Then use the plugin:

// ./server.js file
var request = require('superagent');
var config = require('./superagent-mock-config');

// Before tests
var superagentMock = require('superagent-mock')(request, config);

...

// After tests
superagentMock.unset();

Supported methods

All request methods are supported (get, put, post, etc.).

Each request method mock have to be declared in the config file. Otherwise, the callback method is used.

Logging

You can monitor each call, that has been intercepted by superagent-mock or not, by passing a callback function at initialization.

// ./server.js file
var request = require('superagent');
var config = require('./superagent-mock-config');

var logger = function(log)  {
  console.log('superagent call', log);
};

// Before tests
var superagentMock = require('superagent-mock')(request, config, logger);

...

// After tests
superagentMock.unset();

The callback function will be called with an object containing the following informations

  • data : data used with superagent.send function
  • headers : array of headers given by superagent.set function
  • matcher : regex matching the current url which is defined in the provided config
  • url : url which superagent was called
  • method : HTTP method used for the call
  • timestamp : timestamp of the superagent call
  • mocked : true if the call was mocked by superagent mock, false if it used superagent real methods

Development scripts

To run units tests: yarn test.

To check code style: yarn lint.

To build code: yarn build.

Credits

Developped by the Cytron Team of Bedrock Streaming. Tested with Jest.

License

superagent-mock is licensed under the MIT license.

More Repositories

1

websocket-bench

⛔️ DEPRECATED - nodejs tool to benchmark socket.io and faye websocket server
JavaScript
675
star
2

PhpProcessManagerBundle

⛔ DEPRECATED - PHP ProcessManagerBundle
PHP
98
star
3

RedisMock

A simple PHP Redis mock
PHP
81
star
4

Tornado

A library for asynchronous programming 🌪️ 🐎
PHP
81
star
5

Coke

⛔ DEPRECATED - PHP Code Sniffer configurator
Shell
68
star
6

ApiExceptionBundle

⛔ DEPRECATED - Exception API Bundle
PHP
65
star
7

GithubTeamReviewer

Review all pull requests of your teams in one place
JavaScript
63
star
8

Firewall

⛔ DEPRECATED - Library providing IP filtering features
PHP
62
star
9

DaemonBundle

Allows you to create daemonized commands. 😈
PHP
59
star
10

StatsdBundle

Symfony bundle proving a statsd service and smooth integration in sf2
PHP
55
star
11

tech.bedrockstreaming.com

Bedrock Tech Blog
JavaScript
38
star
12

prescaling-exporter

Prometheus Exporter to scale plateform
Go
31
star
13

CassandraBundle

⛔ DEPRECATED - Symfony bundle on top of the datastax cassandra component
PHP
30
star
14

JenkinsLight

Buildwall for Jenkins
JavaScript
27
star
15

picturefill-background

An inspiration of picturefill using background image and not img tag
JavaScript
23
star
16

ElasticsearchBundle

Integration of the Elasticsearch official PHP client within a Symfony Project
PHP
22
star
17

FirewallBundle

⛔ DEPRECATED - Symfony bundle providing IP filtering features
PHP
22
star
18

Babitch

⛔️ DEPRECATED - Babitch is a project to record table soccer scores, archive them, and make them easily accessible for further analysis using a REST API.
PHP
22
star
19

LogBridgeBundle

Symfony Bundle to log Request/Response with Monolog.
PHP
19
star
20

roboxt

⛔ DEPRECATED - simple parser for robots.txt
PHP
19
star
21

VigoJS

⛔️ DEPRECATED - Make easily functional tests on web applications
JavaScript
18
star
22

JenkinsTerminalColors

Chrome extension that provides standard terminal colors in the Console panel of Jenkins
CSS
18
star
23

GuzzleHttpBundle

Symfony bundle on top of Guzzle
PHP
17
star
24

AmqpBundle

Amqp client as a Symfony Service
PHP
17
star
25

bemlinter

A cli tool to lint bem component isolation in CSS / SCSS files
JavaScript
16
star
26

forms

react.js form generation and validation libraries based on react-hook-form
TypeScript
14
star
27

Statsd

PHP component easing the statsd usage
PHP
13
star
28

behat-seo-extension

⛔ DEPRECATED - behat extension dedicated to seo
PHP
12
star
29

git-hooks

Hooks git used by M6Web tech team
Shell
11
star
30

toothpick-ksp

A KSP code generator for the Toothpick dependency injection library.
Kotlin
11
star
31

RedisMessageBroker

⛔ DEPRECATED - PHP Component to deal with message in Redis 📄
PHP
10
star
32

eslint-tools

BedrockStreaming's ESLint packages
TypeScript
10
star
33

pr-size-labeler

Github action to automatically add label on PR to define size (based on line diff and file modified)
TypeScript
9
star
34

DomainUserBundle

⛔ DEPRECATED - User authentication by domain
PHP
9
star
35

ElasticsearchMock

⛔ DEPRECATED - Library providing a PHP mock for Elasticsearch-php
PHP
9
star
36

KafkaBundle

⛔ DEPRECATED - Apache Kafka Bundle 🚕
PHP
8
star
37

RedisBundle

Symfony2 Bundle over predis
PHP
8
star
38

HttpToStatsd

A node.js http to statsd logger
JavaScript
8
star
39

php-cs-fixer-config

Configuration for https://github.com/FriendsOfPhp/PHP-CS-Fixer
PHP
8
star
40

eslint-plugin-m6web-i18n

ESLint plugin for i18n
JavaScript
8
star
41

hsdo

HAProxy Service Discovery Operator
Python
7
star
42

MonologExtraBundle

PHP
7
star
43

BabitchClient

⛔️ DEPRECATED - BabitchClient provides a simple responsive user interface for Babitch (Foosball API)
JavaScript
7
star
44

DraftjsBundle

⛔️ DEPRECATED
PHP
7
star
45

GitHubEnterpriseArchive

⛔️ DEPRECATED - Archive and graph your GithubEnterprise timeline
PHP
7
star
46

Redis

⛔ DEPRECATED - Component bind on top of predis
PHP
6
star
47

immutable-set

JavaScript
6
star
48

PhpLint

⛔ DEPRECATED - simple command to lint some php 🍔
PHP
5
star
49

alerts-validator

Helps defining which Prometheus alert is working and which is not
Go
5
star
50

ldoups

Go
4
star
51

i18n-tools

M6 WEB's i18n packages
JavaScript
4
star
52

drinkjs

A Medium-like rich text editor based on DraftJS
JavaScript
4
star
53

iab

Stuff about iab framework
3
star
54

StatsdTagsPrometheusBundle

Statsd Bundle With tags (DataDog Format) - For Prometheus
PHP
3
star
55

RateLimitBundle

PHP
3
star
56

eslint-plugin-m6web-tools

JavaScript
3
star
57

XRequestUidBundle

⛔ DEPRECATED - generating call traces in the microservices hell
PHP
3
star
58

sprintf-mock

sprintf-js plugin allowing to mock sprintf behaviour by returning data fixtures based on the resolved pattern
JavaScript
3
star
59

AwsBundle

PHP
3
star
60

StaleCacheBundle

Stale cache feature on top of symfony/cache
PHP
3
star
61

HttpKernelBundle

⛔ DEPRECATED - Custom Symfony HttpKernel
PHP
3
star
62

sparktest

A testing tool for Scala and Spark developers
Scala
2
star
63

ApcuBundle

PHP
2
star
64

HttpToGelf

A node.js http to gelf logger
JavaScript
1
star
65

netapp-exporter

A Prometheus NetApp exporter that exports lots of usefull metrics for both hardware state and volumes
Go
1
star
66

FOSRestExtraBundle

Extra features for the FOSRestBundle
PHP
1
star
67

uptime-multimail

Multi-email plugin for Uptime by @fzaninotto
JavaScript
1
star
68

dash-player

M6web dash player
JavaScript
1
star
69

timecode

Deal with timecode manipulation
PHP
1
star
70

eslint-config-m6web

M6Web configuration for eslint
JavaScript
1
star
71

WsClientBundle

PHP
1
star
72

eslint-tools-m6web

Brings prettier and eslint with airbnb guiding style in only one dependency
1
star
73

android-recruitment-test

1
star
74

uptime-hipchat

Hipchat plugin for Uptime by @fzaninotto
JavaScript
1
star