├── .babelrc ├── .eslintrc ├── .gitignore ├── .npmignore ├── .travis.yml ├── README.md ├── package.json └── src ├── main ├── index.js └── servers │ ├── express.js │ └── hapi.js └── test ├── invalid-hostname.test.js ├── servers ├── express-server.test.js ├── hapi-server.test.js └── schema.js ├── setup.js └── swapi └── simple-swapi.tests.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "es2015" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "rules": { 4 | "valid-jsdoc": [2, { 5 | "requireReturn": false, 6 | "requireParamDescription": true, 7 | "requireReturnDescription": true 8 | }], 9 | "default-case": 2, 10 | "dot-location": [2, "property"], 11 | "no-else-return": 2, 12 | "no-floating-decimal": 2, 13 | "no-param-reassign": 2, 14 | "no-process-env": 2, 15 | "no-undefined": 2, 16 | "comma-style": [2, "last"], 17 | "linebreak-style": [2, "unix"], 18 | "no-lonely-if": 2, 19 | "no-multiple-empty-lines": [2, { 20 | "max": 2 21 | }], 22 | "no-nested-ternary": 2, 23 | "no-var": 2, 24 | "quotes": [2, "single", "avoid-escape"], 25 | "no-console": 0, 26 | "no-trailing-spaces": [2, {"skipBlankLines": true}], 27 | "new-cap": [2, { 28 | "newIsCap": true, 29 | "capIsNew": false 30 | }] 31 | }, 32 | "env": { 33 | "es6": true, 34 | "node": true 35 | }, 36 | "ecmaFeatures": { 37 | "jsx": true, 38 | "modules": true 39 | }, 40 | "plugins": [ 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 18 | .grunt 19 | 20 | # node-waf configuration 21 | .lock-wscript 22 | 23 | # Compiled binary addons (http://nodejs.org/api/addons.html) 24 | build/Release 25 | 26 | # Dependency directory 27 | node_modules 28 | 29 | # Optional npm cache directory 30 | .npm 31 | 32 | # Optional REPL history 33 | .node_repl_history 34 | lib/ 35 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sazzer/graphql-tester/afd2d6b8d2516c19271f9e073c6b671f1a6a3b14/.npmignore -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "5" 4 | - "6" 5 | - "7" 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | GraphQL Tester 2 | ============== 3 | [![Build Status](https://travis-ci.org/sazzer/graphql-tester.svg?branch=master)](https://travis-ci.org/sazzer/graphql-tester) 4 | 5 | Test Framework for executing integration tests against GraphQL Services. 6 | 7 | Example 8 | ------- 9 | This example works against the live SWAPI Implementation available on http://graphql-swapi.parseapp.com. There is a real test, using [Mocha](http://mochajs.org) and [Chai](http://chaijs.com) for this under src/test/swapi/simple-swapi.tests.js 10 | 11 | ```javascript 12 | import {tester} from 'graphql-tester'; 13 | 14 | const test = tester({ 15 | url: 'http://graphql-swapi.parseapp.com' 16 | }); 17 | 18 | // This tests a successful request for the name of person 1 19 | test('{person(personID: 1) { name } }') 20 | .then((response) => { 21 | assert(response.success == true); 22 | assert(response.status == 200); 23 | assert(response.data.person.name == 'Luke Skywalker'); 24 | }); 25 | 26 | // This tests a request for the name of non-existant person 1234 27 | test('{person(personID: 1234) { name } }') 28 | .then((response) => { 29 | assert(response.success == false); 30 | assert(response.status == 200); 31 | }); 32 | 33 | // This tests a malformed query 34 | test('{person(personId: 1) { name } }') 35 | .then((response) => { 36 | assert(response.success == false); 37 | assert(response.status == 400); 38 | }); 39 | ``` 40 | 41 | API 42 | --- 43 | At it's core, this library allows you to make a request to a service and perform assertions on the response. The way that the request query is generated, and the response is asserted is entirely up to you. The above example uses a simple string for the query, and the core *assert* method. However, there is no need to use these mechanisms and you can use whatever makes the most sense for your tests. 44 | 45 | ### tester 46 | The "tester" function is used to create a function that can be used to test a specific API. At creation time it is given all of the details needed to call the API, and then it can be used to make requests and get responses from the API. This function takes a single Object as a parameter, with the following keys: 47 | 48 | * url - The URL to make requests to. This is required. This must be absolute if the "server" parameter is not provided, and should be relative to the Base URL of the server if the "server" parameter is provided. 49 | * server - The configuration for starting an application server to test against. This is optional, but if present then the url must be relative to this server. 50 | * method - The HTTP Method to use for the requests. This is optional, and will default to POST 51 | * contentType - The Content Type Header to set for the requests. This is optional, and will default to "application/graphql" 52 | 53 | This function will return a function that can be used to make requests to the API. This returned function takes: 54 | 55 | * a GraphQL Query to execute 56 | * an optional [request options Object](https://github.com/request/request#requestoptions-callback) that will add to and override the default options 57 | 58 | It will return a Promise for the response from the server. This Promise will be resolved with an Object containing: 59 | * success - True if the query was a success. False if not. Note that in this case Success means there was no "errors" element returned. 60 | * status - The HTTP Status Code of the response received. 61 | * headers - The HTTP Headers of the response received. 62 | * raw - The raw response that was received. 63 | * data - The "data" element in the response from the server, if present. 64 | * errors - The "errors" element in the response from the server, if present. 65 | 66 | If there was a catastrophic failure in making the request - connection refused, for example - then the Promise will instead be rejected. 67 | 68 | Note that because a Promise is returned you get some benefits here. You can use this promise as a return in certain promise-aware testing tools - e.g. Mocha. You can also use the same promise to make assertions fit better into some BDD style tests. 69 | 70 | #### "server" parameter 71 | When the "tester" function is used to create the GraphQL Tester to use, it is possible to pass in an Application Server configuration. This configuration will be used to start up an Application Server before each test is run, execute the query against this server and then shut the server down. Helper functions are provided to configure an Application Server for use with Express 4.x and HapiJS. Any other server can be used though, as long as you provide the configuration yourself. 72 | 73 | ##### Express 4.x 74 | An example of testing against an Express Server can be seen in src/test/servers/express-server.test.js. 75 | 76 | In order to configure the tester to work against an Express server, you simply need to use the "create" function exported from the "graphql-tester/servers/express" module. This function is called with the configured but not-yet-running Express server, and returns the full configuration to pass in to the "server" property of the "tester" function. 77 | 78 | ##### HapiJS 79 | An example of testing against a HapiJS Server can be seen in src/test/servers/hapi-server.test.js. 80 | 81 | In oder to configure the tester to work against a HapiJS Server, you simply need to use the "create" function exported from the "graphql-tester/servers/hapi" module. This function is called with the plugin configuration to configure HapiJS with - this can be anything that you can legally pass to Hapi.Server.Register - and will return the full configuration to pass in to the "server" property of the "tester" function. 82 | 83 | ##### Arbitrary Application servers 84 | It is possible to use any arbitrary application server by providing the configuration yourself. This configuration currently takes the form of a Javascript Object that has a single key of "creator". This key is a function that is called with the port number to listen on - this will be dynamically generated every test - and should return a Promise for the server configuration. This server configuration should be a Javascript object that has keys of: 85 | * url - The base URL of the server. Note that this is *not* the URL to the GraphQL endpoint - that should be passed in to the "url" property of the "tester" function as usual, but should be relative to this Base URL. 86 | * server - This is a Javascript object with a single key - "shutdown" - which is a function to shut the running server down at the end of the test. This is optional, but if not provided then it will not be possible to shut the servers down and eventually the test process is likely to crash from a lack of resources. 87 | 88 | Note that because of how this works, it is possible to start a server before the tests run and re-use it between all tests - simply return the URL to the singleton server and never return a function to shut it down. This might be useful in some circumstances but it greatly increases the likelihood of cross-contamination of tests. 89 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphql-tester", 3 | "version": "0.0.5", 4 | "description": "Test Framework for executing integration tests against GraphQL Services", 5 | "main": "lib/main/index.js", 6 | "scripts": { 7 | "clean": "rm -rf lib", 8 | "compile": "babel src/main -d lib/main", 9 | "test-compile": "babel src/test -d lib/test", 10 | "pretest-compile": "npm run compile", 11 | "preunittest": "npm run test-compile", 12 | "unittest": "mocha -G --recursive --require lib/test/setup lib/test", 13 | "lint": "eslint src", 14 | "test": "npm run lint && npm run unittest", 15 | "prepublish": "npm run clean && npm run test" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "git+https://github.com/sazzer/graphql-tester.git" 20 | }, 21 | "keywords": [ 22 | "graphql", 23 | "test" 24 | ], 25 | "author": "Graham Cox ", 26 | "license": "ISC", 27 | "bugs": { 28 | "url": "https://github.com/sazzer/graphql-tester/issues" 29 | }, 30 | "homepage": "https://github.com/sazzer/graphql-tester#readme", 31 | "devDependencies": { 32 | "babel-cli": "^6.4.5", 33 | "babel-eslint": "^7.0.0", 34 | "babel-preset-es2015": "^6.3.13", 35 | "chai": "^3.5.0", 36 | "chai-as-promised": "^6.0.0", 37 | "eslint": "^3.8.0", 38 | "express": "^4.13.4", 39 | "express-graphql": "^0.5.4", 40 | "graphql": "^0.7.2", 41 | "hapi": "^15.1.1", 42 | "hapi-graphql": "^1.0.1", 43 | "mocha": "^3.1.2" 44 | }, 45 | "dependencies": { 46 | "freeport": "^1.0.5", 47 | "request": "^2.69.0" 48 | }, 49 | "engines": { 50 | "node": ">=4.0.0" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/index.js: -------------------------------------------------------------------------------- 1 | import request from 'request'; 2 | import freeport from 'freeport'; 3 | 4 | export function tester({ 5 | url, 6 | server, 7 | method = 'POST', 8 | contentType = 'application/graphql', 9 | authorization = null 10 | }) { 11 | return (query, requestOptions) => { 12 | return new Promise((resolve, reject) => { 13 | if (server) { 14 | freeport((err, port) => { 15 | if (err) { 16 | reject(err); 17 | } else { 18 | resolve(server.creator(port) 19 | .then((runningServer) => { 20 | return { 21 | server: runningServer.server, 22 | url: runningServer.url + url 23 | } 24 | })); 25 | } 26 | }); 27 | } else { 28 | resolve({ 29 | url 30 | }); 31 | } 32 | }).then(({url, server}) => { 33 | return new Promise((resolve, reject) => { 34 | let headers = { 35 | 'Content-Type': contentType, 36 | }; 37 | if (authorization !== null) headers['Authorization'] = authorization; 38 | let options = { method, uri: url, headers, body: query }; 39 | options = Object.assign(options, requestOptions); 40 | request(options, (error, message, body) => { 41 | if (server && typeof(server.shutdown) === 'function') { 42 | server.shutdown(); 43 | } 44 | 45 | if (error) { 46 | reject(error); 47 | } else { 48 | const result = JSON.parse(body); 49 | 50 | resolve({ 51 | raw: body, 52 | data: result.data, 53 | errors: result.errors, 54 | headers: message.headers, 55 | status: message.statusCode, 56 | success: !result.hasOwnProperty('errors') 57 | }); 58 | } 59 | }); 60 | }); 61 | }); 62 | }; 63 | } 64 | -------------------------------------------------------------------------------- /src/main/servers/express.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Create an Express.js wrapper that can be used for running tests against 3 | * @param {Application} app The Express.js Application that should be used to test against 4 | * @return {Object} configuration to pass to the GraphQL Tester for using this server 5 | */ 6 | export function create(app) { 7 | return { 8 | creator: (port) => { 9 | return new Promise((resolve, reject) => { 10 | const server = app.listen(port, () => { 11 | resolve({ 12 | server: { 13 | shutdown: () => { 14 | server.close(); 15 | } 16 | }, 17 | url: `http://localhost:${port}` 18 | }); 19 | }); 20 | }); 21 | } 22 | }; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/servers/hapi.js: -------------------------------------------------------------------------------- 1 | import Hapi from 'hapi'; 2 | 3 | /** 4 | * Create a HapiJS wrapper that can be used for running tests against 5 | * @param {Object|Array} plugins The HapiJS plugins to register against the instance 6 | * @return {Object} configuration to pass to the GraphQL Tester for using this server 7 | */ 8 | export function create(plugins) { 9 | return { 10 | creator: (port) => { 11 | const server = new Hapi.Server(); 12 | server.connection({ 13 | port 14 | }); 15 | 16 | return server.register(plugins) 17 | .then(() => server.start()) 18 | .then(() => { 19 | return { 20 | server: { 21 | shutdown: () => { 22 | server.stop(); 23 | } 24 | }, 25 | url: server.info.uri 26 | }; 27 | }); 28 | } 29 | }; 30 | } 31 | -------------------------------------------------------------------------------- /src/test/invalid-hostname.test.js: -------------------------------------------------------------------------------- 1 | import {tester} from '../main'; 2 | 3 | describe('Invalid Hostname', () => { 4 | let InvalidHostnameTest = tester({ 5 | url: 'http://i.dont.exist.grahamcox.co.uk' 6 | }); 7 | 8 | describe('Valid Query to Invalid Host', () => { 9 | const response = InvalidHostnameTest('{ person(personID: 1) { name } }'); 10 | 11 | it('Promise is rejected', () => { 12 | return response.should.eventually.be.rejected; 13 | }); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /src/test/servers/express-server.test.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import GraphQL from 'express-graphql'; 3 | import {create as createExpressWrapper} from '../../main/servers/express'; 4 | import {TestSchema} from './schema'; 5 | import {tester} from '../../main'; 6 | 7 | describe('Express Server', () => { 8 | const app = express(); 9 | app.use('/express/graphql', GraphQL({ 10 | schema: TestSchema 11 | })); 12 | 13 | const ExpressTest = tester({ 14 | server: createExpressWrapper(app), 15 | url: '/express/graphql' 16 | }); 17 | 18 | describe('Valid Query', () => { 19 | const response = ExpressTest('{ test(who: "Graham") }'); 20 | 21 | it('Returns success', () => { 22 | return response.should.eventually.have.property('success').equal(true); 23 | }); 24 | it('Returns the correct Status code', () => { 25 | return response.should.eventually.have.property('status').equal(200); 26 | }); 27 | it('Returns the correct name', () => { 28 | return response.should.eventually.have.deep.property('data.test').equal('Hello Graham'); 29 | }); 30 | }); 31 | 32 | describe('Invalid Query', () => { 33 | const response = ExpressTest('{ somethingElse(who: "Graham") }'); 34 | 35 | it('Returns success', () => { 36 | return response.should.eventually.have.property('success').equal(false); 37 | }); 38 | it('Returns the correct Status code', () => { 39 | return response.should.eventually.have.property('status').equal(400); 40 | }); 41 | it('Returns some errors', () => { 42 | return response.should.eventually.have.property('errors'); 43 | }); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /src/test/servers/hapi-server.test.js: -------------------------------------------------------------------------------- 1 | import GraphQL from 'hapi-graphql'; 2 | import {create as createHapiWrapper} from '../../main/servers/hapi'; 3 | import {TestSchema} from './schema'; 4 | import {tester} from '../../main'; 5 | 6 | describe('Hapi Server', () => { 7 | const HapiTest = tester({ 8 | server: createHapiWrapper([ 9 | { 10 | register: GraphQL, 11 | options: { 12 | query: { 13 | schema: TestSchema, 14 | rootValue: {}, 15 | pretty: false 16 | }, 17 | route: { 18 | path: '/hapi/graphql', 19 | config: {} 20 | } 21 | } 22 | } 23 | ]), 24 | url: '/hapi/graphql' 25 | }); 26 | 27 | describe('Valid Query', () => { 28 | const response = HapiTest('{ test(who: "Graham") }'); 29 | 30 | it('Returns success', () => { 31 | return response.should.eventually.have.property('success').equal(true); 32 | }); 33 | it('Returns the correct Status code', () => { 34 | return response.should.eventually.have.property('status').equal(200); 35 | }); 36 | it('Returns the correct name', () => { 37 | return response.should.eventually.have.deep.property('data.test').equal('Hello Graham'); 38 | }); 39 | }); 40 | 41 | describe('Invalid Query', () => { 42 | const response = HapiTest('{ somethingElse(who: "Graham") }'); 43 | 44 | it('Returns success', () => { 45 | return response.should.eventually.have.property('success').equal(false); 46 | }); 47 | it('Returns the correct Status code', () => { 48 | return response.should.eventually.have.property('status').equal(400); 49 | }); 50 | it('Returns some errors', () => { 51 | return response.should.eventually.have.property('errors'); 52 | }); 53 | }); 54 | }); 55 | -------------------------------------------------------------------------------- /src/test/servers/schema.js: -------------------------------------------------------------------------------- 1 | import { 2 | GraphQLObjectType, 3 | GraphQLString, 4 | GraphQLNonNull, 5 | GraphQLSchema 6 | } from 'graphql'; 7 | 8 | const QueryRootType = new GraphQLObjectType({ 9 | name: 'QueryRoot', 10 | fields: { 11 | test: { 12 | type: GraphQLString, 13 | args: { 14 | who: { 15 | type: GraphQLString 16 | } 17 | }, 18 | resolve: (root, { who }) => 'Hello ' + (who || 'World') 19 | }, 20 | thrower: { 21 | type: new GraphQLNonNull(GraphQLString), 22 | resolve: () => { throw new Error('Throws!'); } 23 | } 24 | } 25 | }); 26 | 27 | export const TestSchema = new GraphQLSchema({ 28 | query: QueryRootType 29 | }); 30 | -------------------------------------------------------------------------------- /src/test/setup.js: -------------------------------------------------------------------------------- 1 | import chai from 'chai'; 2 | import chaiAsPromised from 'chai-as-promised'; 3 | 4 | chai.should(); 5 | chai.use(chaiAsPromised); 6 | -------------------------------------------------------------------------------- /src/test/swapi/simple-swapi.tests.js: -------------------------------------------------------------------------------- 1 | import {tester} from '../../main'; 2 | 3 | describe('SWAPI', () => { 4 | let SwapiTest = tester({ 5 | url: 'http://graphql-swapi.parseapp.com' 6 | }); 7 | 8 | describe('Successfully getting the name of Person #1', () => { 9 | const response = SwapiTest('{ person(personID: 1) { name } }'); 10 | 11 | it('Returns success', () => { 12 | return response.should.eventually.have.property('success').equal(true); 13 | }); 14 | it('Returns the correct Status code', () => { 15 | return response.should.eventually.have.property('status').equal(200); 16 | }); 17 | it('Returns the correct name', () => { 18 | return response.should.eventually.have.deep.property('data.person.name').equal('Luke Skywalker'); 19 | }); 20 | }); 21 | 22 | describe('Getting the name of Person #1234', () => { 23 | const response = SwapiTest('{ person(personID: 1234) { name } }'); 24 | 25 | it('Returns failure', () => { 26 | return response.should.eventually.have.property('success').equal(false); 27 | }); 28 | it('Returns the correct Status code', () => { 29 | return response.should.eventually.have.property('status').equal(200); 30 | }); 31 | it('Returns some errors', () => { 32 | return response.should.eventually.have.property('errors'); 33 | }); 34 | }); 35 | 36 | describe('Incorrect argument requested', () => { 37 | const response = SwapiTest('{ person(personId: 1) { name } }'); 38 | 39 | it('Returns failure', () => { 40 | return response.should.eventually.have.property('success').equal(false); 41 | }); 42 | it('Returns the correct Status code', () => { 43 | return response.should.eventually.have.property('status').equal(400); 44 | }); 45 | it('Returns some errors', () => { 46 | return response.should.eventually.have.property('errors'); 47 | }); 48 | }); 49 | }); 50 | --------------------------------------------------------------------------------