Manual Reference Source Test

test/unit/helpers.event.js

import test from 'ava';
import nock from 'nock';
import {
  client,
  Event,
  Rule,
} from '../../src';


// See tests.js for testing client creation
// const rule = new Rule({ id: 67 });
// rule.store();

test.before('start server', (t) => {
  client.apiBaseUrl = 'https://somesite.Clinical6.com';
  client.authToken = 'valid_token';

  // patch response
  t.context.updateResponse = {
    data: {
      id: 7,
      type: 'reminder__events',
      attributes: {
        date: '2016-06-06T00:00:00Z',
        status: 5,
        extras: null,
        created_at: '2017-09-12T05:36:52Z',
        updated_at: '2017-09-12T05:36:52Z'
      },
      relationships: {
        mobile_user: {
          data: {
            id: 215,
            type: 'mobile_users'
          }
        },
        rule: {
          data: {
            id: 19,
            type: 'reminder__rules'
          }
        }
      }
    }
  };

  // insertResponse
  t.context.insertResponse = {
    data: {
      id: 32,
      type: 'reminder__events',
      attributes: {
        date: '2016-06-06T00:00:00Z',
        status: 5,
        extras: null,
        created_at: '2017-09-12T05:35:12Z',
        updated_at: '2017-09-12T05:35:12Z'
      },
      relationships: {
        mobile_user: {
          data: null
        },
        rule: {
          data: {
            id: 67,
            type: 'reminder__rules'
          }
        }
      }
    }
  };
});

test.beforeEach((t) => {
  client.cache = 'never';
  client.authToken = 'valid_token';
  // t.context.server = sinon.fakeServer.create();
  // t.context.server.autoRespond = true;

  // eventJsonApi
  t.context.eventJsonApi = {
    id: 32,
    type: 'reminder__events',
    attributes: {
      date: '2016-06-06T00:00:00Z',
      status: 5,
      extras: null,
      created_at: '2017-09-12T05:35:12Z',
      updated_at: '2017-09-12T05:35:12Z'
    },
    relationships: {
      mobile_user: {
        data: null
      },
      rule: {
        data: {
          id: 67,
          type: 'reminder__rules'
        }
      }
    }
  };

  // eventJson
  t.context.eventJson = {
    id: 32,
    type: 'reminder__events',
    date: '2016-06-06T00:00:00Z',
    status: 5,
    extras: null,
    created_at: '2017-09-12T05:35:12Z',
    updated_at: '2017-09-12T05:35:12Z',
    relationships: {
      mobile_user: {
        data: null
      },
      rule: {
        data: {
          id: 67,
          type: 'reminder__rules'
        }
      }
    }
  };

  t.context.reportedActionJsonApi = {
    action: 'callback',
    resource: 'patient',
    context: {
      value: 'approved'
    }
  };


  // t.context.server.respondWith('DELETE', `${client.apiBaseUrl}/v3/reminder/events/*`,
  //   [200, { 'Content-Type': 'application/json' }, JSON.stringify({ status: 'ok' })]
  // );

  // t.context.server.respondWith('GET', `${client.apiBaseUrl}/v3/reminder/events`,
  //   [200, { 'Content-Type': 'application/json' }, JSON.stringify({
  //     data: [
  //       {
  //         id: '33',
  //         type: 'reminder__events',
  //         attributes: {
  //           date: '2016-06-06T00:00:00Z',
  //           status: 5,
  //           extras: null,
  //           created_at: '2017-09-12T05:35:12Z',
  //           updated_at: '2017-09-12T05:35:12Z'
  //         },
  //         relationships: {
  //           mobile_user: {
  //             data: null
  //           },
  //           rule: {
  //             data: {
  //               id: '68',
  //               type: 'reminder__rules'
  //             }
  //           }
  //         }
  //       },
  //       {
  //         id: '34',
  //         type: 'reminder__events',
  //         attributes: {
  //           date: '2016-06-06T00:00:00Z',
  //           status: 5,
  //           extras: null,
  //           created_at: '2017-09-12T05:35:12Z',
  //           updated_at: '2017-09-12T05:35:12Z'
  //         },
  //         relationships: {
  //           mobile_user: {
  //             data: null
  //           },
  //           rule: {
  //             data: {
  //               id: '69',
  //               type: 'reminder__rules'
  //             }
  //           }
  //         }
  //       },
  //       {
  //         id: '35',
  //         type: 'reminder__events',
  //         attributes: {
  //           date: '2016-06-06T00:00:00Z',
  //           status: 5,
  //           extras: null,
  //           created_at: '2017-09-12T05:35:12Z',
  //           updated_at: '2017-09-12T05:35:12Z'
  //         },
  //         relationships: {
  //           mobile_user: {
  //             data: null
  //           },
  //           rule: {
  //             data: {
  //               id: '70',
  //               type: 'reminder__rules'
  //             }
  //           }
  //         }
  //       }
  //     ]
  //   })]
  // );

  // t.context.server.respondWith('GET', `${client.apiBaseUrl}/v3/reminder/events/*`,
  //   [200, { 'Content-Type': 'application/json' }, JSON.stringify({
  //     data: {
  //       id: '32',
  //       type: 'reminder__events',
  //       attributes: {
  //         date: '2016-06-06T00:00:00Z',
  //         status: 5,
  //         extras: null,
  //         created_at: '2017-09-12T05:35:12Z',
  //         updated_at: '2017-09-12T05:35:12Z'
  //       },
  //       relationships: {
  //         mobile_user: {
  //           data: null
  //         },
  //         rule: {
  //           data: {
  //             id: '67',
  //             type: 'reminder__rules'
  //           }
  //         }
  //       }
  //     }
  //   })]
  // );


  // t.context.server.respondWith('POST', `${client.apiBaseUrl}/v3/reminder/events`,
  //   [201, { 'Content-Type': 'application/json' }, JSON.stringify({
  //     data: {
  //       id: 32,
  //       type: 'reminder__events',
  //       attributes: {
  //         date: '2016-06-06T00:00:00Z',
  //         status: 5,
  //         extras: null,
  //         created_at: '2017-09-12T05:35:12Z',
  //         updated_at: '2017-09-12T05:35:12Z'
  //       },
  //       relationships: {
  //         mobile_user: {
  //           data: null
  //         },
  //         rule: {
  //           data: {
  //             id: '67',
  //             type: 'reminder__rules'
  //           }
  //         }
  //       }
  //     }
  //   })]
  // );


  t.context.storage = client.storageUtility;

  // // See tests.js for testing client creation
  // const rule = new Rule({ id: 67 });
  // rule.store();
  // const eventJsonApi = {
  //   id: 32,
  //   type: 'reminder__events',
  //   attributes: {
  //     date: '2016-06-06T00:00:00Z',
  //     status: 5,
  //     extras: null,
  //     created_at: '2017-09-12T05:35:12Z',
  //     updated_at: '2017-09-12T05:35:12Z'
  //   },
  //   relationships: {
  //     mobile_user: {
  //       data: null
  //     },
  //     rule: {
  //       data: {
  //         id: '67',
  //         type: 'reminder__rules'
  //       }
  //     }
  //   }
  // };

  // const eventJson = {
  //   id: 32,
  //   type: 'reminder__events',
  //   date: '2016-06-06T00:00:00Z',
  //   status: 5,
  //   extras: null,
  //   created_at: '2017-09-12T05:35:12Z',
  //   updated_at: '2017-09-12T05:35:12Z',
  //   relationships: {
  //     mobile_user: {
  //       data: null
  //     },
  //     rule: {
  //       data: {
  //         id: '67',
  //         type: 'reminder__rules'
  //       }
  //     }
  //   }
  // };


  // t.context.eventJsonApi = {
  //   data: {
  //     id: '32',
  //     type: 'reminder__events',
  //     attributes: {
  //       date: '2016-06-06T00:00:00Z',
  //       status: 5,
  //       extras: null,
  //       created_at: '2017-09-12T05:35:12Z',
  //       updated_at: '2017-09-12T05:35:12Z'
  //     },
  //     relationships: {
  //       mobile_user: {
  //         data: null
  //       },
  //       rule: {
  //         data: {
  //           id: '67',
  //           type: 'reminder__rules'
  //         }
  //       }
  //     }
  //   }
  // };
  t.context.event = new Event(t.context.eventJsonApi);
});

// test.afterEach(t => t.context.server.restore());

/**
 * @test {Event}
 */
test('[unit] Event should handle event data with a normal json format', async (t) => {
  const { eventJson } = t.context;
  const event = new Event({ data: eventJson });
  await event.syncRelationships();
  t.truthy(event);
  t.is(event.id, 32);
  t.is(event.type, 'reminder__events');
  t.is(event.createdAt, '2017-09-12T05:35:12Z');
  t.is(event.updatedAt, '2017-09-12T05:35:12Z');
  t.is(event.date, '2016-06-06T00:00:00Z');
  t.is(event.status, 5);
  t.is(event.rule.id, 67);
  t.is(event.rule.type, 'reminder__rules');
});

/**
 * @test {Event}
 */
test('[unit] Event should handle event data with json api format', async (t) => {
  const { eventJsonApi } = t.context;
  await new Rule({ id: 67 }).store();
  const event = new Event({ data: eventJsonApi });
  await event.syncRelationships();
  t.truthy(event);
  t.is(event.id, 32);
  t.is(event.type, 'reminder__events');
  t.is(event.createdAt, '2017-09-12T05:35:12Z');
  t.is(event.updatedAt, '2017-09-12T05:35:12Z');
  t.is(event.date, '2016-06-06T00:00:00Z');
  t.is(event.status, 5);
  t.is(event.rule.id, 67);
  t.is(event.rule.type, 'reminder__rules');
});

/**
 * @test {Event}
 */
test('[unit] Event should generate json api format when converted to string', async (t) => {
  const { eventJsonApi } = t.context;
  let event = new Event({ data: eventJsonApi });
  await event.syncRelationships();
  t.deepEqual(event.toJSON(), eventJsonApi);

  event = new Event({ data: eventJsonApi });
  await event.syncRelationships();
  t.deepEqual(event.toJSON(), eventJsonApi);
});

/**
 * @test {Event.delete}
 */
test('[unit] Event.delete should successfully delete an event', async (t) => {
  const { eventJsonApi } = t.context;
  const event = new Event({ data: eventJsonApi });
  let request = {};

  // mock delete response
  nock(client.apiBaseUrl).delete(`/v3/reminder/events/${event.id}`).reply(function (uri, requestBody) {
    request = this.req;
    request.requestBody = requestBody;
    return [200, ''];
  });

  // const request = t.context.server.requests[0];
  // t.is(request.method, 'DELETE');
  // t.is(request.url, `${client.apiBaseUrl}/v3/reminder/events/${event.id}`);
  // t.is(request.requestHeaders.Accept, 'application/json');
  // t.is(request.requestHeaders['Content-Type'], 'application/json;charset=utf-8');
  // t.is(request.requestHeaders.Authorization, 'Token token=valid_token');
  const response = await event.delete();

  t.is(request.path, `/v3/reminder/events/${event.id}`);
  t.is(request.headers.accept, 'application/json');
  t.is(request.headers['content-type'], 'application/json');
  t.is(request.headers.authorization, 'Token token=valid_token');
  t.falsy(response);
});

/**
 * @test {Event.save}
 */
test('[unit] Event.save should successfully insert an event with an event object when id does not exist', async (t) => {
  const { eventJsonApi, insertResponse } = t.context;
  const json = JSON.parse(JSON.stringify(eventJsonApi));
  delete json.id;
  const event = new Event({ data: json });
  let request = {};
  nock(client.apiBaseUrl).post(`/v3/reminder/events`).reply(function (uri, requestBody) {
    request = this.req;
    request.requestBody = requestBody;
    return [201, insertResponse];
  });
  await event.syncRelationships();
  await event.save();

  // const request = t.context.server.requests[0];
  // t.is(request.method, 'POST');
  // t.is(request.url, `${client.apiBaseUrl}/v3/reminder/events`);
  // t.is(request.requestHeaders.Accept, 'application/json');
  // t.deepEqual(JSON.parse(request.requestBody), { data: json });
  // t.is(request.requestHeaders['Content-Type'], 'application/json;charset=utf-8');
  // t.is(request.requestHeaders.Authorization, 'Token token=valid_token');
  t.is(request.path, `/v3/reminder/events`);
  t.is(request.headers.accept, 'application/json');
  t.deepEqual(request.requestBody, { data: json });
  t.is(request.headers['content-type'], 'application/json');
  t.is(request.headers.authorization, 'Token token=valid_token');
  t.truthy(event);

  t.is(event.id, 32);
  t.is(event.type, 'reminder__events');
  t.is(event.createdAt, '2017-09-12T05:35:12Z');
  t.is(event.updatedAt, '2017-09-12T05:35:12Z');
  t.is(event.date, '2016-06-06T00:00:00Z');
  t.is(event.status, 5);
  t.is(event.rule.id, 67);
  t.is(event.rule.type, 'reminder__rules');
});

/**
 * @test {Event.save}
 */
test('[unit] Event.save should successfully update a event with a event object when an id exists', async (t) => {
  const { eventJsonApi, updateResponse } = t.context;
  const event = new Event({ data: eventJsonApi });
  let request = {};
  nock(client.apiBaseUrl).patch(`/v3/reminder/events/${event.id}`).reply(function (uri, requestBody) {
    request = this.req;
    request.requestBody = requestBody;
    return [200, updateResponse];
  });

  const response = await event.save();
  t.is(request.path, `/v3/reminder/events/${event.id}`);
  t.is(request.headers.accept, 'application/json');
  t.deepEqual(request.requestBody, { data: eventJsonApi });
  t.is(request.headers.authorization, 'Token token=valid_token');
  t.is(response.id, 7);
  t.is(response.type, 'reminder__events');
});

/**
 * @test {Event.saveEventAction}
 */
test('[unit] Event.saveEventAction should successfully submit this event to track', async (t) => {
  const { reportedActionJsonApi } = t.context;
  const event = new Event({ data: reportedActionJsonApi });
  const json = JSON.parse(JSON.stringify(reportedActionJsonApi));
  nock(client.apiBaseUrl).post(`/api/v2/event/reported_actions`).reply(204, {
    action: 'callback',
    resource: 'patient',
    context: {
      value: 'approved'
    }
  });
  const response = await event.saveEventAction(json.resource, json.action, json.context.value);
  t.is(response.action, 'callback');
  t.is(response.resource, 'patient');
  t.is(response.context.value, 'approved');
  // t.is(response.action, 'callback');
  // t.is(response.resource, 'patient');
  // t.is(response.context.value, 'approved');
});

/**
 * @test {EventService.trackEvents}
 */
// test('[unit] EventService.trackEvents should reply with a friendly error message for missing/invalid tokens', async (t) => {
//   nock(client.apiBaseUrl).post(`/api/v2/event/reported_actions`).reply(404, {
//     error_detail: 'Trigger not found: invalid_value',
//     friendly_error: 'Trigger not found using the value:Trigger not found',
//     internal_code: 50364,
//     more_info: '',
//     status: 'fail',
//     message: 'Trigger not found using the value:Trigger not found'
//   });
//   const response = await eventService.trackEvents().catch(r => r);
//   t.is(response.status, 'fail');
//   t.is(response.details, 'Trigger not found: invalid_value');
//   t.is(response.friendly, 'Trigger not found using the value:Trigger not found');
//   t.is(response.code, 50364);
// });