Manual Reference Source Test

test/unit/client.js

import test from 'ava';
import nock from 'nock';
import {
  Clinical6,
  client,
  Client
} from '../../src';

/**
 * @test {Client}
 */
test('[unit] Client exists', async (t) => {
  await t.truthy(Client);
});

/**
 * @test {Client}
 */
test('[unit] Client.instance() should not allow the creation of the instance', async (t) => {
  await t.throws(() => {
    const myClient = new Client();
    myClient.instance = 'test';
  }, 'Cannot construct singleton');
});

/**
 * @test {Client}
 */
test('[unit] Client.instance() should return the instance of client', async (t) => {
  const myClinical6 = new Clinical6();
  await t.is(Client.instance, myClinical6.Client);
});

/**
 * @test {Client}
 */
test('[unit] Client should throw an error if instantiated with a non-string baseurl', async (t) => {
  await t.throws(() => {
    client.apiBaseUrl = 123;
  }, 'Clinical6 error : apiBaseUrl must be a string');
});

/**
 * @test {Client}
 */
test('[unit] Client should construct an instance instantiated with baseurl', async (t) => {
  client.apiBaseUrl = 'http://myurl.com';
  await t.truthy(client);
  await t.is(client.apiBaseUrl, 'http://myurl.com');
  await t.is(client.authToken, undefined);
});

/**
 * @test {Client}
 */
test('[unit] Client should have a fetch method', async (t) => {
  client.apiBaseUrl = 'http://myurl.com';
  await t.truthy(client);
  await t.truthy(client.fetch);
});

/**
 * @test {Client}
 */
test('[unit] Client should throw an error on fetch when data is not present in put call', async (t) => {
  client.apiBaseUrl = 'http://myurl.com';
  const expectedError = 'Clinical6 fetch error: invalid PUT/POST request, no data given';
  await t.throws(() => client.fetch('/this/is/a/random/endpoint', 'put'), expectedError);
});

/**
 * @test {Client}
 */
test('[unit] Client should handle unauthorized request', async (t) => {
  client.apiBaseUrl = 'http://myurl.com';
  let response;
  let status;
  Client.instance.onError = (s, r) => {
    status = s;
    response = r;
  };
  nock(client.apiBaseUrl).get('/this/is/a/random/endpoint').reply(401);
  await t.throwsAsync(client.fetch('/this/is/a/random/endpoint')).then(async () => {
    await t.truthy(response);
    await t.is(status, 401);
  });
});