'use strict' const test = require('ava') const { stub } = require('sinon') const Hapi = require('@hapi/hapi') const plugin = require('../lib/plugins/profile') const Profile = require('../lib/models/profile') const ZipCode = require('../lib/models/zip-code') const MatchQueue = require('../lib/models/matchqueue') // !: Must match the key set in servives/profile.js const zipcodeKey = 7 /** * Route parameters */ const params = { profile_id: 1, max_distance: 1000, } const mockReturn = { user: [ { profile_id: 1, user: { is_poster: 1 }, responses: [ { val: '120' }, { val: '200' }, { response_key_id: zipcodeKey, val: '90065' }, ], }, { profile_id: 2, user: { is_poster: 0 }, responses: [ { val: '120' }, { val: '200' }, { response_key_id: zipcodeKey, val: '96741' }, ], }, { profile_id: 3, user: { is_poster: 0 }, responses: [ { val: '180' }, { val: '140' }, { response_key_id: zipcodeKey, val: '97002' }, ], }, ], } const pathToTest = { method: 'GET', url: `/${params.profile_id}/score?max_distance=${params.max_distance}`, } test(`path ${pathToTest.url} should return ok on GET`, async t => { /** * Create a new server and register services, * models and routes for testing * - * NOTE: We use a mocked registerModel() and register * models manually. Normally this is handled by * Schwifty at runtime. */ const server = Hapi.server() /** * Overload so we don't register any models * using the plugin call (see plugins/profile.js) * and Manually load the model we need for the test */ server.registerModel = () => {} server.models = () => ({ MatchQueue, Profile, ZipCode }) /** * Register Routes and Services as usual */ await plugin.register(server) /** * Replace Objection model methods with our own mock functions * !: Janky - might be better to temp knex sqlite instance */ stub(server.models()['Profile'], 'query').returns({ // Mocked for pathToTest(), scoreProfilesFor() findOne: () => ({ withGraphFetched: () => ({ withGraphFetched: () => mockReturn.user[0], }), }), // Mocked for scoreProfilesFor() withGraphFetched: () => ({ withGraphFetched: () => [mockReturn.user[1], mockReturn.user[2]], }), // Mocked for _getProfileIdsForUserId() where: () => ({}), // Mocked for getCompleteProfilesFor(), getProfilesFor() whereIn: () => ({ withGraphFetched: () => ({}), }), // Mocked for deleteProfile() delete: () => ({ where: () => ({}), }), }) stub(server.models()['ZipCode'], 'query').returns({ // Mocked for _latLonForZip() findOne: () => ({ latitude: 38.0 + Math.random(), longitude: -121.0 + Math.random(), }), }) stub(server.models()['MatchQueue'], 'query').returns({ patch: () => ({ where: () => ({}), }), insert: () => ({}), where: () => ({ andWhere: () => ({}), }), }) /** * Test the server with registered models and services */ const { payload } = await server.inject(pathToTest) const res = JSON.parse(payload) t.deepEqual(res.ok, true) t.is(res.data.length, 2) t.is(res.data[0].profile_id, 3) })