@xervo/api-util
Version:
wrapper to make API request simpler
137 lines (112 loc) • 3.3 kB
JavaScript
const Assign = require('lodash.assign');
const Code = require('code');
const Lab = require('lab');
const Nock = require('nock');
const API = require('..');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;
const beforeEach = lab.beforeEach;
const afterEach = lab.afterEach;
const HEADERS = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'API-Version': 'v2'
};
describe('API', function () {
var client, scope;
beforeEach(function (done) {
Nock.disableNetConnect();
done();
});
afterEach(function (done) {
Nock.cleanAll();
Nock.enableNetConnect();
done();
});
it('exports a function', function (done) {
expect(API).to.be.a.function();
done();
});
describe('called with no options', function () {
beforeEach(function (done) {
client = API();
scope = Nock('https://api.xervo.io', {
reqheaders: Assign({}, HEADERS)
});
// eslint-disable-next-line no-magic-numbers
scope.get('/').reply(200, { test: true });
done();
});
it('returns a default client', function (done) {
client.get('/', function (err, result) {
expect(err).to.not.exist();
expect(result).to.deep.equal({ test: true });
done();
});
});
});
describe('called with custom API', function () {
beforeEach(function (done) {
client = API({
hostname: 'api.example.com',
protocol: 'http',
port: 8080 // eslint-disable-line no-magic-numbers
});
scope = Nock('http://api.example.com:8080', {
reqheaders: Assign({}, HEADERS)
});
// eslint-disable-next-line no-magic-numbers
scope.get('/').reply(200, { test: true });
done();
});
it('returns a custom client', function (done) {
client.get('/', function (err, result) {
expect(err).to.not.exist();
expect(result).to.deep.equal({ test: true });
done();
});
});
});
describe('when using a instance token', function () {
beforeEach(function (done) {
client = API({ token: '1234' });
scope = Nock('https://api.xervo.io', {
reqheaders: Assign({}, HEADERS, {
'Authorization': 'Token 1234'
})
});
// eslint-disable-next-line no-magic-numbers
scope.get('/').reply(200, { test: true });
done();
});
it('binds the token to all requests', function (done) {
client.get('/', function (err, result) {
expect(err).to.not.exist();
expect(result).to.deep.equal({ test: true });
done();
});
});
});
describe('when setting a custom API version', function () {
beforeEach(function (done) {
client = API({ version: 'v3' });
scope = Nock('https://api.xervo.io', {
reqheaders: Assign({}, HEADERS, {
'API-Version': 'v3'
})
});
// eslint-disable-next-line no-magic-numbers
scope.get('/').reply(200, { test: true });
done();
});
it('it works', function (done) {
client.get('/', function (err, result) {
expect(err).to.not.exist();
expect(result).to.deep.equal({ test: true });
done();
});
});
});
});