Просмотр исходного кода

:gear: writing and adjusting backend tests

tags/0.0.1
TOJ 4 лет назад
Родитель
Сommit
bbb060d767

+ 2
- 1
.gitignore Просмотреть файл

@@ -5,4 +5,5 @@ dist-ssr
5 5
 *.local
6 6
 **/.env
7 7
 .nyc_output
8
-**/generated/*
8
+**/generated/*
9
+**/.vscode

+ 2
- 0
backend/lib/routes/profile/update.js Просмотреть файл

@@ -46,6 +46,7 @@ module.exports = {
46 46
 
47 47
             /** Grab payload info */
48 48
             const res = request.payload
49
+
49 50
             try {
50 51
                 const updatedResponses =
51 52
                     await profileService.updateResponsesInProfile(
@@ -56,6 +57,7 @@ module.exports = {
56 57
                 if (!updatedResponses) {
57 58
                     throw new RangeError('Response not updated')
58 59
                 }
60
+
59 61
                 return h
60 62
                     .response({
61 63
                         ok: true,

+ 4
- 4
backend/lib/services/profile.js Просмотреть файл

@@ -43,7 +43,7 @@ const scoreAll = (profileList, userProfile) => {
43 43
  * Grab the zip code string
44 44
  */
45 45
 const getZipCodeFromProfile = profile => {
46
-    console.log('profile getZipCode', profile)
46
+    // console.log('profile getZipCode', profile)
47 47
     // There should only be one zip code entry per profile
48 48
     let zipRes = profile.responses.filter(
49 49
         // Whatever the zipcode questions is
@@ -198,7 +198,7 @@ module.exports = class ProfileService extends Schmervice.Service {
198 198
             return null
199 199
         }
200 200
 
201
-        await await Response.query().insert(responseToSave)
201
+        await Response.query().insert(responseToSave)
202 202
         return allResponses
203 203
     }
204 204
 
@@ -241,7 +241,7 @@ module.exports = class ProfileService extends Schmervice.Service {
241 241
         let profileIdsOfOppositeType = await Profile.query()
242 242
             .withGraphFetched('responses')
243 243
             .withGraphFetched('user')
244
-        
244
+
245 245
         // TODO: Let Objection optimize this
246 246
         const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
247 247
         profileIdsOfOppositeType = profileIdsOfOppositeType.filter(
@@ -257,7 +257,7 @@ module.exports = class ProfileService extends Schmervice.Service {
257 257
         const profilePlusDistance = await Promise.all(
258 258
             profileIdsOfOppositeType.map(async profile => {
259 259
                 const targetZip = getZipCodeFromProfile(profile)
260
-                
260
+
261 261
                 if(!userZip || !targetZip) return { ...profile, distance: [9999, distanceUnit] }
262 262
 
263 263
                 const distance = await this._compareDistance(

+ 1
- 1
backend/package.json Просмотреть файл

@@ -11,7 +11,7 @@
11 11
     "reseed": "knex migrate:rollback --all && knex migrate:latest && knex seed:run",
12 12
     "generate": "node ./db/data-generator/index.js",
13 13
     "seed": "knex seed:run",
14
-    "test": "nyc ava --timeout=3000"
14
+    "test": "nyc ava --timeout=5000"
15 15
   },
16 16
   "author": "TOJ",
17 17
   "license": "UNLICENSED",

+ 1
- 1
backend/tests/matchqueue.spec.js Просмотреть файл

@@ -28,7 +28,7 @@ const pathToTest = {
28 28
     url: `/${params.profile_id}/queue/${params.target_id}/delete?include_profile=${params.include_profile}&reinsert=${params.reinsert}`,
29 29
 }
30 30
 
31
-test('path / should return ok on GET', async t => {
31
+test('path /<profile_id>/queue/<target_id> should return ok on PATCH', async t => {
32 32
     /**
33 33
      * Create a new server and register services,
34 34
      * models and routes for testing

+ 54
- 0
backend/tests/notification.spec.js Просмотреть файл

@@ -0,0 +1,54 @@
1
+'use strict'
2
+
3
+const test = require('ava')
4
+const Hapi = require('@hapi/hapi')
5
+
6
+const plugin = require('../lib/plugins/notification')
7
+
8
+/**
9
+ * Route parameters
10
+ */
11
+const params = {
12
+    profile_id: 37
13
+}
14
+const mockReturn = {
15
+    queue: [
16
+        { mocked_profile_id: 1, target_id: 2, is_deleted: false },
17
+        { mocked_profile_id: 2, target_id: 3, is_deleted: false },
18
+        { mocked_profile_id: 3, target_id: 1, is_deleted: false },
19
+    ],
20
+}
21
+const pathToTest = {
22
+    method: 'GET',
23
+    url: `/${params.profile_id}/subscribe`,
24
+}
25
+
26
+test('path /subscribe should return ok on GET', async t => {
27
+    /**
28
+     * Create a new server and register services,
29
+     * models and routes for testing
30
+     * -
31
+     * NOTE: We use a mocked registerModel() and register
32
+     * models manually. Normally this is handled by
33
+     * Schwifty at runtime.
34
+     */
35
+    const server = Hapi.server()
36
+
37
+    /**
38
+     * Register Routes and Services as usual
39
+     */
40
+    await plugin.register(server)
41
+
42
+    /**
43
+     * Test the server with registered models and services
44
+     */
45
+    const { payload } = await server.inject(pathToTest)
46
+    console.log('---')
47
+    console.log(payload)
48
+    const res = JSON.parse(payload)
49
+    t.deepEqual(res.ok, true)
50
+    t.deepEqual(
51
+        res.data,
52
+        mockReturn.queue.map(entry => entry.target_id),
53
+    )
54
+})

+ 82
- 0
backend/tests/respond.spec.js Просмотреть файл

@@ -0,0 +1,82 @@
1
+'use strict'
2
+
3
+const test = require('ava')
4
+const { stub } = require('sinon')
5
+const Hapi = require('@hapi/hapi')
6
+
7
+const plugin = require('../lib/plugins/profile')
8
+
9
+const Response = require('../lib/models/response')
10
+const ResponseKey = require('../lib/models/response-key')
11
+/**
12
+ * Route parameters
13
+ */
14
+const params = {
15
+    profile_id: 38
16
+}
17
+const mockReturn = {
18
+    responses: [
19
+        {
20
+            response_id: 1,
21
+            profile_id: 38,
22
+            response_key_id: 6,
23
+            val: '400'
24
+        },
25
+        {
26
+            response_id: 2,
27
+            profile_id: 38,
28
+            response_key_id: 7,
29
+            val: '90012'
30
+        }
31
+    ],
32
+}
33
+const pathToTest = {
34
+    method: 'POST',
35
+    url: `/${params.profile_id}/respond?response_key_id=5&val=999`,
36
+}
37
+
38
+test('path /<profile_id>/respond should return ok on POST', async t => {
39
+    /**
40
+     * Create a new server and register services,
41
+     * models and routes for testing
42
+     * -
43
+     * NOTE: We use a mocked registerModel() and register
44
+     * models manually. Normally this is handled by
45
+     * Schwifty at runtime.
46
+     */
47
+    const server = Hapi.server()
48
+    /**
49
+     * Overload so we don't register any models
50
+     * using the plugin call (see plugins/profile.js)
51
+     * and Manually load the model we need for the test
52
+     */
53
+    server.registerModel = () => {}
54
+    server.models = () => ({ Response, ResponseKey })
55
+    /**
56
+     * Register Routes and Services as usual
57
+     */
58
+    await plugin.register(server)
59
+    /**
60
+     * Replace Objection model methods with our own mock functions
61
+     * !: Janky - might be better to temp knex sqlite instance
62
+     */
63
+    stub(server.models()['Response'], 'query').returns({
64
+        where: () => mockReturn.responses,
65
+        insert: response => {
66
+            response.response_id = 3
67
+            mockReturn.responses.push(response)
68
+        }
69
+    })
70
+
71
+
72
+    /**
73
+     * Test the server with registered models and services
74
+     */
75
+    const { payload } = await server.inject(pathToTest)
76
+    const res = JSON.parse(payload)
77
+    t.deepEqual(res.ok, true)
78
+    t.deepEqual(
79
+        res.data,
80
+        mockReturn.responses,
81
+    )
82
+})

+ 2
- 2
backend/tests/score.spec.js Просмотреть файл

@@ -11,7 +11,7 @@ const ZipCode = require('../lib/models/zip-code')
11 11
 const MatchQueue = require('../lib/models/matchqueue')
12 12
 
13 13
 // !: Must match the key set in servives/profile.js
14
-const zipcodeKey = 7 
14
+const zipcodeKey = 7
15 15
 
16 16
 /**
17 17
  * Route parameters
@@ -56,7 +56,7 @@ const pathToTest = {
56 56
     url: `/${params.profile_id}/score?max_distance=${params.max_distance}`,
57 57
 }
58 58
 
59
-test(`path ${pathToTest.path} should return ok on GET`, async t => {
59
+test(`path ${pathToTest.url} should return ok on GET`, async t => {
60 60
     /**
61 61
      * Create a new server and register services,
62 62
      * models and routes for testing

+ 103
- 0
backend/tests/update.spec.js Просмотреть файл

@@ -0,0 +1,103 @@
1
+'use strict'
2
+
3
+const test = require('ava')
4
+const { stub } = require('sinon')
5
+const Hapi = require('@hapi/hapi')
6
+
7
+const plugin = require('../lib/plugins/profile')
8
+
9
+const Response = require('../lib/models/response')
10
+const ResponseKey = require('../lib/models/response-key')
11
+/**
12
+ * Route parameters
13
+ */
14
+const params = {
15
+    profile_id: 38
16
+}
17
+const mockReturn = {
18
+    responses: [
19
+        {
20
+            response_id: 1,
21
+            profile_id: 38,
22
+            response_key_id: 6,
23
+            val: '400'
24
+        },
25
+        {
26
+            response_id: 2,
27
+            profile_id: 38,
28
+            response_key_id: 7,
29
+            val: '90012'
30
+        }
31
+    ],
32
+}
33
+const pathToTest = {
34
+    method: 'PATCH',
35
+    url: `/${params.profile_id}/update/1`,
36
+    payload: [
37
+        {
38
+            response_id: 1,
39
+            profile_id: 38,
40
+            response_key_id: 6,
41
+            val: '999'
42
+        },
43
+        {
44
+            response_id: 2,
45
+            profile_id: 38,
46
+            response_key_id: 7,
47
+            val: '999'
48
+        }
49
+    ]
50
+}
51
+
52
+test(`path ${pathToTest.url} should return ok on ${pathToTest.method}`, async t => {
53
+    /**
54
+     * Create a new server and register services,
55
+     * models and routes for testing
56
+     * -
57
+     * NOTE: We use a mocked registerModel() and register
58
+     * models manually. Normally this is handled by
59
+     * Schwifty at runtime.
60
+     */
61
+    const server = Hapi.server()
62
+    /**
63
+     * Overload so we don't register any models
64
+     * using the plugin call (see plugins/profile.js)
65
+     * and Manually load the model we need for the test
66
+     */
67
+    server.registerModel = () => {}
68
+    server.models = () => ({ Response, ResponseKey })
69
+    /**
70
+     * Register Routes and Services as usual
71
+     */
72
+    await plugin.register(server)
73
+    /**
74
+     * Replace Objection model methods with our own mock functions
75
+     * !: Janky - might be better to temp knex sqlite instance
76
+     */
77
+    stub(server.models()['Response'], 'query').returns({
78
+        where: () => {
79
+            mockReturn.responses.forEach(res => {
80
+                res.val = '999'
81
+            })
82
+            return mockReturn.responses
83
+        },
84
+        update: () => ({
85
+            where: () => ({
86
+                where: () => {}
87
+            })
88
+        })
89
+    })
90
+
91
+
92
+    /**
93
+     * Test the server with registered models and services
94
+     */
95
+    const { payload } = await server.inject(pathToTest)
96
+    const res = JSON.parse(payload)
97
+
98
+    t.deepEqual(res.ok, true)
99
+    t.deepEqual(
100
+        res.data,
101
+        mockReturn.responses,
102
+    )
103
+})

Загрузка…
Отмена
Сохранить