• Stars
    star
    556
  • Rank 79,706 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated almost 2 years ago

Reviews

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

Repository Details

End-to-end API testing made easy

NPM version Build Status Code Climate

hippie

Synopsis

Thin request wrapper that enables powerful and intuitive API testing.

Features

  • Intuitive and consistent API
  • Built-in and custom expectations
  • Support for custom parsers and serializers
  • Easy to extend
  • Middlewares
  • Works great with any test runner

Examples

var api = require('hippie');

Hello world

hippie()
.header("User-Agent", "hippie")
.json()
.get('https://api.github.com/users/vesln')
.expectStatus(200)
.end(function(err, res, body) {
  if (err) throw err;
});

Expectations

hippie()
.json()
.base('http://localhost:1234')
.get('/users/vesln')
.expectStatus(200)
.expectHeader('Content-Type', 'application/json; charset=utf-8')
.expectKey('username')
.expectValue('username', 'vesln')
.expectValue('repos[0].name', 'jsmd')
.expectBody({
  username: 'vesln',
  repos: [
    { name: 'jsmd' },
    { name: 'hippie' },
  ]
})
.expectBody(/vesln/g)
.end(function(err, res, body) {
  if (err) throw err;
  process.exit(0);
});

Middlewares

hippie()
.json()
.use(function(options, next) {
  // modify the options for `request` here
  next(options);
})
.get('https://api.github.com/users/vesln')
.end(function(err, res, body) {
  if (err) throw err;
});

With middlewares you can modify the options passed to request. Here is an example how you could persist the cookies across multiple requests:

hippie(app)
.get('/')
.use(persistCookies)
.end(function() {});

function persistCookies(opts, next) {
  opts.jar = true;
  next(opts);
}

Serializers and parsers

var xml = require('my-xml-library');

hippie()
.serializer(function(params, fn) {
  var err = new Error('Things went wrong');
  var res = xml.objectToXml(params);
  fn(err, res);
})
.parser(function(body, fn) {
  var err = new Error('Things went wrong');
  var res = xml.xmlToObject(body);
  fn(err, res);
})
.get('https://api.github.com/users/vesln.xml')
.expectStatus(200)
.end(function(err, res, body) {
  if (err) throw err;
});

AssertionError configurations

Similar to Chai.js and other frameworks, you can enable showDiff.

var hippie = require('hippie');
hippie.assert.showDiff = true;

showDiff

DRY

Since most of the time your test setup is going to be the same, you can simply create a helper function for your tests that will take care of the repetitive setup:

var hippie = require('hippie');

function api() {
  return hippie()
    .json()
    .serializer(customSerializer)
    .parser(customParser)
    .use(somethingSpecial)
    .base('http://localhost:3000/api/v1')
    .auth('user', 'pass')
    .expect(somethingRepeatable);
}

Later on:

test('my awesome api', function(done) {
  api()
  .get('/users')
  .expectStatus(200)
  .end();
});

API

#timeout

Configure a timeout for the HTTP request.

hippie()
.timeout(1000)
.end(fn);

#time

Configure response time logging for the HTTP request.

hippie()
.time(true)
.end(function(err, res, body) {
  console.log('Response elapsed time: ', res.elapsedTime);
});

#qs

Convert an object to query string values:

hippie()
.qs({ foo: 'bar' })
.end(fn);

#base

Configure a base URL, useful when testing the same API endpoint.

hippie()
.base('https://api.github.com')
.get('/users/vesln')
.end(fn);

#url

Set the URL for the HTTP request. Used internally by get, put etc. and it should be used in combination with method.

hippie()
.url('https://api.github.com')
.method('GET')
.end(fn);

#method

Configure the HTTP method. Used internally by get, put etc.

hippie()
.url('https://api.github.com')
.method('OPTIONS')
.end(fn);

#header

Set a request header.

hippie()
.header('Content-Type', 'application/json')
.send({ some: 'data' })
.end(fn);

#json

Helper method for:

  • Content-Type: application/json
  • Accept: application/json
  • Serializer: json
  • Parser: json
hippie()
.json()
.get('https://github.com/vesln.json', fn);

#form

Helper method for:

  • Content-Type: application/x-www-form-urlencoded
  • Serializer: urlencoded
hippie()
.form()
.patch('https://api.mindbloom.com/users/vesln')
.send({ timezone: 'UTC' })
.end();

#serializer

Configure a request body serializer.

hippie()
.serializer(function(params, fn) {
  var err = new Error('Things went wrong');
  var res = xml.objectToXml(params);
  fn(err, res);
});

#parser

Configure a response body parser.

hippie()
.parser(function(body, fn) {
  var err = new Error('Things went wrong');
  var res = xml.xmlToObject(body);
  fn(err, res);
});

#send

Set request body.

hippie()
.json()
.patch('https://api.mindbloom.com/users/vesln')
.send({ timezone: 'UTC' })
.end();

#auth

Set Basic Auth credentials.

hippie()
.auth('user', 'password')
.patch('https://api.mindbloom.com/users/vesln')
.send({ timezone: 'UTC' })
.end();

#use

Register a middleware that will be executed before the HTTP request.

hippie()
.json()
.use(function(options, next) {
  // modify the options for `request` here
  // do other suff
  next(options);
})
.get('https://api.github.com/users/vesln')
.end(fn);

For example, you can provide a client certificate with your request like so:

var fs = require('fs');
hippie()
 .json()
 .use(function(options, next) {
  options.agentOptions = {
   cert: fs.readFileSync('client.crt'),
   key: fs.readFileSync('client.key')
  };
  // Assuming you self-signed the CA
  options.strictSSL = false;
  next(options);
 })
 .get('https://localhost:8080/api/some-api-url')
 .end(fn);

#get, #del, #post, #put, #patch, #head

Helper method for:

  • Method: method
  • URL: url
  • End: fn [optional]
hippie()
.get('https://api.github.com/users/vesln')
.end(fn);

Or if you want to execute the test immediately:

hippie()
.get('https://api.github.com/users/vesln', fn);

#expectStatusCode, #expectStatus, #expectCode

Set a response status code expectation.

hippie()
.json()
.get('https://api.github.com/users/vesln')
.expectStatus(200)
.end(fn);

#expectHeader

Set a response header expectation.

hippie()
.json()
.get('https://api.github.com/users/vesln')
.expectHeader('Content-Type', 'application/json; charset=utf-8')
.expectHeader('X-API-LIMIT', 3)
.end(fn);

#expectValue

Register a string path expectation.

hippie()
.json()
.get('https://api.github.com/users/vesln')
.expectValue('details.company', 'Awesome.io')
.expectValue('repos[0].name', 'hippie')
.end(fn);

For more information about string paths visit pathval.

#expectKey

Register a string path expectation for a given key.

hippie()
.json()
.get('https://api.github.com/users/vesln')
.expectKey('details.company')
.expectKey('repos[0].name')
.end(fn);

For more information about string paths visit pathval.

#expectBody

Strict expectations:

hippie()
.get('https://api.github.com/users/vesln')
.expectBody('{ "username": "vesln" }')
.end(fn);

Regular expression expectations:

hippie()
.get('https://api.github.com/users/vesln')
.expectBody(/vesln/)
.end(fn);

Object/array expectations:

hippie()
.get('https://api.github.com/users/vesln')
.expectBody({ username: 'vesln' })
.end(fn);

#expect

Register a custom expectation.

hippie()
.get('https://api.github.com/users/vesln')
.expect(function(res, body, next) {
  var err = assertSomething;
  next(err);
})
.end(fn);

#end

Execute the HTTP request and the tests.

hippie()
.json()
.get('https://api.github.com/users/vesln')
.expectValue('details.company', 'Awesome.io')
.expectValue('repos[0].name', 'hippie')
.end(fn);

When no callback is provided, end() returns a promise.

hippie()
.json()
.get('https://api.github.com/users/vesln')
.expectValue('details.company', 'Awesome.io')
.expectValue('repos[0].name', 'hippie')
.end()
.then(function(res) {
  console.log(res);
})
.catch(function(err) {
  console.error(err);
});

#app

Fire up an HTTP app and set its address as a base URL. Also works with HTTP handler functions function(req res){}.

hippie(expressApp)
.get('/')
.end(fn);
hippie()
.app(function(req, res) {
  res.end('Bye');
})
.get('/')
.end(fn);

Installation

npm install hippie

Tests

Running the tests

$ npm test

Test coverage

$ npm run-script coverage

Alternative projects

License

(The MIT License)

Copyright (c) 2013 Veselin Todorov [email protected]

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.

More Repositories

1

timekeeper

Easy testing of time-dependent code. Node.js
JavaScript
423
star
2

todo

Todos in the CLI like what.
JavaScript
400
star
3

nixt

Simple and elegant end-to-end testing for command-line apps
JavaScript
308
star
4

issues

GitHub Issues from the CLI.
JavaScript
211
star
5

r...e

Powerful Range implementation. Node.js & browsers
JavaScript
93
star
6

logme

Minimalistic logger for Node.js.
JavaScript
89
star
7

teacher

Spell check for Node.js
JavaScript
79
star
8

bot

Feeling lonely? You personal bot is here.
JavaScript
68
star
9

temporary

Temporary files and dirs for Node.js
JavaScript
68
star
10

sourcery

Consume any RESTful API with just a few lines of JavaScript
JavaScript
66
star
11

word

Functions that assist in working with strings. Node.js
CoffeeScript
56
star
12

pin

Is my site up? Node.js edition.
JavaScript
55
star
13

curiosity

Curious metrics about your JavaScript project
JavaScript
51
star
14

jsmd

jsmd ensures that you will never have outdated and non-working JavaScript code in your README files.
JavaScript
50
star
15

jack

Test-double framework for Node.js and browsers
JavaScript
41
star
16

fine

Tiny, recursive and synchronous file finder utility
JavaScript
35
star
17

moni

Process monitoring with node.
JavaScript
29
star
18

robber.py

BDD / TDD assertion library for Python
Python
29
star
19

let

Force timeouts. Node.js.
JavaScript
27
star
20

b

Benchmarks for Node.js
JavaScript
26
star
21

package

Easy package.json exports.
JavaScript
24
star
22

cyclop

Highly focused async. Does one thing... like a boss.
JavaScript
20
star
23

captureme

CLI utility that helps you capture screenshots via browsers in the cloud
JavaScript
19
star
24

box

Powerful key -> value storage for the CLI.
JavaScript
15
star
25

hell

Experimental complexity analyzer for JavaScript projects
JavaScript
11
star
26

mill

Readable milliseconds for you and other humans. Node.js
JavaScript
11
star
27

structure

Struct generator. Node.js
JavaScript
10
star
28

storr

The most simple JSON storage created ever.
JavaScript
9
star
29

hydro

JavaScript
9
star
30

.dotfiles

Ponnies!
Vim Script
9
star
31

core_ext

JavaScript extensions.
JavaScript
8
star
32

redr

Lazy require with filter logic for Node.js
JavaScript
7
star
33

seed-forge

Factory builder for Mongoose & Seed
JavaScript
6
star
34

surround

Surround a method, save a polar bear.
JavaScript
6
star
35

times

times loop for your coffee.
CoffeeScript
6
star
36

refractory

Thin require wrapper that will allow you to load files from conventional paths
JavaScript
6
star
37

obsessed

Retry mechanism for Node.js and the browsers
JavaScript
5
star
38

tryc

Async try-catch for browsers and Node.js
JavaScript
4
star
39

decorator

JavaScript decorators. POW! Arrghhh!
JavaScript
4
star
40

babel-plugin-react-auto-display-name

Add displayName to React.createClass calls
JavaScript
4
star
41

gist-client

GitHub Gists from the cli.
JavaScript
4
star
42

exports

Easy data exports to your client-side scripts.
JavaScript
4
star
43

socialcount

Get social stats for given url
JavaScript
4
star
44

eyehurt

Color utility for zombies
JavaScript
3
star
45

racks

Reusable middleware implementation for Node.js & the browsers.
JavaScript
3
star
46

freedom

Mind-blowing issue tracker powered by Ruby on Rails.
Ruby
3
star
47

evts

Minimal event emitter implementation that supports both sync and async event handlers
JavaScript
3
star
48

koa-http-logger

koa http request & response logger
JavaScript
2
star
49

printr

Print utils
JavaScript
2
star
50

mini

Minimalistic test runner
JavaScript
2
star
51

chai-mongoose

Mongoose model assertions for chai.js
JavaScript
2
star
52

vim-swag

Turn your swag on. Dark color scheme for Vim
Vim Script
2
star
53

stylec

JavaScript
1
star
54

gorilla

JavaScript
1
star
55

globalo

Top-level object detector for Node.js, Titanium, Titanium + Alloy, browsers
JavaScript
1
star
56

to-date

Time ago/from now date generator
JavaScript
1
star
57

jstore

Minimalistic JSON-based persistence layer
JavaScript
1
star
58

generator-mod

Yeoman Node.js module generator
JavaScript
1
star
59

homepath

$HOME
JavaScript
1
star
60

seltron

Tiny Selenium spawner
JavaScript
1
star
61

pcal

Go
1
star
62

surround.rb

Ruby port of surround.js
Ruby
1
star
63

vim-sws

Example code from "Testing Vim plugins with Vimrunner and RSpec" on Vim Ninjas
Ruby
1
star
64

fload

JavaScript file loader for browsers and Node.js
JavaScript
1
star
65

copycat

HTTP request and response recorder
JavaScript
1
star