0.0.0 • Published 6 years ago

api-examples v0.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
6 years ago

Api Examples

Common utils for api examples

Add to my code

Add to your package.json

npm install api-examples

How it works

We lean on convention to minimise code.

As a producer

New up ApiExamples with your service name.

Then when you want to produce an api example from an e2e test:

  • write your e2e test you normally would
  • call save with: a test name, the request and the response 1

This will write a request and response json output to:

__apiExamples/${serviceName}/${example-name}

For example the below:

it('saves hotel config', async () => {
    const postResponse = await request.post(`${baseUrl}/hotels`, {
      json: { apiKey: 'hotel api key', client: 'hotel client' },
      resolveWithFullResponse: true,
    });
    expect(postResponse.statusCode).toBe(201);

    apiExamples.save('hotel-config', postResponse.request, postResponse.request.response); // [1]
});

will publish to a file called __apiExamples/figgy/hotel-config.json:

{
  "request": {
    "method": "POST",
    "path": "/hotels"
  },
  "response": {
    "statusCode": 201,
    "statusMessage": "Created",
    "headers": {
      "content-type": "application/json; charset=utf-8",
      "content-length": "50",
      "date": "Thu, 07 Jun 2018 16:08:11 GMT",
      "connection": "close"
    },
    "body": {
      "apiKey": "hotel api key",
      "client": "hotel client"
    }
  }
}

As part of your build you rsync the folder to gcp bucket api-examples:

gsutil -m rsync -cr __apiExamples gs://api-examples/

As a consumer

New up ApiExamples with the service name you're testing against.

You can then pull api examples from a gcloud bucket called api-examples. 1

Then match against the examples to get a response 2

You can match on:

  • method
  • path
  • body

Then we can assert on the response 3

const ApiExamples = require('api-examples');
const apiExamples = new ApiExamples('figgy');
const expect = require('expect.js');

describe('figgy', ()=>{

  before(async function() {
    this.timeout(10000);
    await apiExamples.pullApiExamples(); // [1] <--
  });

  it('gives us a hotel from client and property id', async () => {
    const response = await apiExamples.findMatchingExample({  // [2] <--
      method: 'POST'
    });

    expect(response.statusCode).to.be(201); // [3] <--
  })
});