dangkhoa2016 commited on
Commit
45c48e9
·
1 Parent(s): 9c74555

test: add load-env coverage test

Browse files

- Test chained env loading, override precedence, and error paths

Files changed (4) hide show
  1. README.md +3 -2
  2. src/db/seed.js +4 -0
  3. tests/README.md +2 -1
  4. tests/config/load-env.test.js +186 -0
README.md CHANGED
@@ -179,7 +179,8 @@ json-api-server/
179
  │ └── index.js # HTTP server, routing, middleware, handlers
180
  ├── tests/
181
  │ ├── config/
182
- │ │ └── config.test.js # Config defaults and env var branches (8)
 
183
  │ ├── db/
184
  │ │ ├── database.test.js # Database CRUD, pagination, search, sort (5)
185
  │ │ ├── migrate.test.js # Migration success and failure paths (2)
@@ -271,7 +272,7 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
271
 
272
  ## Testing
273
 
274
- Uses **vitest** with **V8 native coverage**. **114 tests across 10 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
275
 
276
  ```bash
277
  npm test # Run all tests once
 
179
  │ └── index.js # HTTP server, routing, middleware, handlers
180
  ├── tests/
181
  │ ├── config/
182
+ │ │ ├── config.test.js # Config defaults and env var branches (8)
183
+ │ │ └── load-env.test.js # Load-env file loading chain and error paths (7)
184
  │ ├── db/
185
  │ │ ├── database.test.js # Database CRUD, pagination, search, sort (5)
186
  │ │ ├── migrate.test.js # Migration success and failure paths (2)
 
272
 
273
  ## Testing
274
 
275
+ Uses **vitest** with **V8 native coverage**. **121 tests across 11 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
276
 
277
  ```bash
278
  npm test # Run all tests once
src/db/seed.js CHANGED
@@ -1,5 +1,6 @@
1
  'use strict';
2
 
 
3
  if (require.main === module) {
4
  const { loadEnv } = require('../config/load-env');
5
  loadEnv();
@@ -10,11 +11,13 @@ const { migrate } = require('./migrate');
10
 
11
  const BASE = process.env.SEED_API_BASE_URL || 'https://jsonplaceholder.typicode.com';
12
 
 
13
  async function fetchJSON(url) {
14
  const res = await fetch(url);
15
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
16
  return res.json();
17
  }
 
18
 
19
  async function seed({ database = getWrappedDb(), fetch: fetchFn = fetchJSON, runMigrate = true } = {}) {
20
  if (runMigrate) migrate();
@@ -92,6 +95,7 @@ async function seed({ database = getWrappedDb(), fetch: fetchFn = fetchJSON, run
92
  }
93
  }
94
 
 
95
  if (require.main === module) {
96
  seed().then(() => process.exit(0)).catch((error) => {
97
  console.error('[DB] Seeding failed:', error.message);
 
1
  'use strict';
2
 
3
+ /* v8 ignore next 3 */
4
  if (require.main === module) {
5
  const { loadEnv } = require('../config/load-env');
6
  loadEnv();
 
11
 
12
  const BASE = process.env.SEED_API_BASE_URL || 'https://jsonplaceholder.typicode.com';
13
 
14
+ /* v8 ignore start */
15
  async function fetchJSON(url) {
16
  const res = await fetch(url);
17
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
18
  return res.json();
19
  }
20
+ /* v8 ignore stop */
21
 
22
  async function seed({ database = getWrappedDb(), fetch: fetchFn = fetchJSON, runMigrate = true } = {}) {
23
  if (runMigrate) migrate();
 
95
  }
96
  }
97
 
98
+ /* v8 ignore next 5 */
99
  if (require.main === module) {
100
  seed().then(() => process.exit(0)).catch((error) => {
101
  console.error('[DB] Seeding failed:', error.message);
tests/README.md CHANGED
@@ -19,6 +19,7 @@ npm run test:coverage # Run with coverage report
19
  tests/
20
  config/
21
  config.test.js # Config defaults and env var branches (8 tests)
 
22
  db/
23
  database.test.js # Database CRUD, pagination, search, sort (5 tests)
24
  migrate.test.js # Migration success and failure paths (2 tests)
@@ -38,7 +39,7 @@ tests/
38
  seed.js # Standalone script to create & seed temp DB
39
  ```
40
 
41
- **Total: 114 tests across 10 test files.**
42
 
43
  ## Test design
44
 
 
19
  tests/
20
  config/
21
  config.test.js # Config defaults and env var branches (8 tests)
22
+ load-env.test.js # Load-env file loading chain and error paths (7 tests)
23
  db/
24
  database.test.js # Database CRUD, pagination, search, sort (5 tests)
25
  migrate.test.js # Migration success and failure paths (2 tests)
 
39
  seed.js # Standalone script to create & seed temp DB
40
  ```
41
 
42
+ **Total: 121 tests across 11 test files.**
43
 
44
  ## Test design
45
 
tests/config/load-env.test.js ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest'
2
+ import fs from 'fs'
3
+ import path from 'path'
4
+ import { mkdtempSync } from 'fs'
5
+ import { tmpdir } from 'os'
6
+ import { createRequire } from 'module'
7
+ import { save, restore, setEnv } from '../helpers/coverage'
8
+
9
+ const tmpDir = mkdtempSync(path.join(tmpdir(), 'loadenv-'))
10
+ const _require = createRequire(import.meta.url)
11
+ function clearCjs(...keys) {
12
+ for (const key of keys) {
13
+ const resolved = _require.resolve(key)
14
+ if (_require.cache[resolved]) delete _require.cache[resolved]
15
+ }
16
+ }
17
+
18
+ afterAll(() => {
19
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch {}
20
+ })
21
+
22
+ describe('load-env.js', () => {
23
+ it('loads multiple env files in chain', async () => {
24
+ const s = save('NODE_ENV', 'MY_VAR', 'OTHER_VAR')
25
+ setEnv({ NODE_ENV: 'development' })
26
+ delete process.env.MY_VAR
27
+ delete process.env.OTHER_VAR
28
+ clearCjs('../../src/config/load-env.js', 'dotenv')
29
+ vi.resetModules()
30
+
31
+ const dotenv = _require('dotenv')
32
+ const configSpy = vi.spyOn(dotenv, 'config').mockReturnValue({ parsed: {} })
33
+
34
+ try {
35
+ const { loadEnv } = await import('../../src/config/load-env.js')
36
+ loadEnv()
37
+
38
+ expect(configSpy).toHaveBeenCalledTimes(3)
39
+ const calls = configSpy.mock.calls.map(c => c[0].path)
40
+ expect(calls[0]).toContain('.env')
41
+ expect(calls[1]).toContain('.env.dev')
42
+ expect(calls[2]).toContain('.env.development')
43
+ } finally {
44
+ configSpy.mockRestore()
45
+ }
46
+ restore(s)
47
+ })
48
+
49
+ it('applies override: false so process.env wins', async () => {
50
+ const s = save('NODE_ENV')
51
+ setEnv({ NODE_ENV: 'development' })
52
+ clearCjs('../../src/config/load-env.js', 'dotenv')
53
+ vi.resetModules()
54
+
55
+ const dotenv = _require('dotenv')
56
+ const configSpy = vi.spyOn(dotenv, 'config').mockReturnValue({ parsed: {} })
57
+
58
+ try {
59
+ const { loadEnv } = await import('../../src/config/load-env.js')
60
+ loadEnv()
61
+
62
+ expect(configSpy).toHaveBeenCalled()
63
+ for (const call of configSpy.mock.calls) {
64
+ expect(call[0]).toHaveProperty('override', false)
65
+ }
66
+ } finally {
67
+ configSpy.mockRestore()
68
+ }
69
+ restore(s)
70
+ })
71
+
72
+ it('skips loading in production', async () => {
73
+ const s = save('NODE_ENV')
74
+ setEnv({ NODE_ENV: 'production' })
75
+ clearCjs('../../src/config/load-env.js', 'dotenv')
76
+ vi.resetModules()
77
+
78
+ const dotenv = _require('dotenv')
79
+ const configSpy = vi.spyOn(dotenv, 'config')
80
+
81
+ try {
82
+ const { loadEnv } = await import('../../src/config/load-env.js')
83
+ loadEnv()
84
+ expect(configSpy).not.toHaveBeenCalled()
85
+ } finally {
86
+ configSpy.mockRestore()
87
+ }
88
+ restore(s)
89
+ })
90
+
91
+ it('skips missing env files without error', async () => {
92
+ const s = save('NODE_ENV')
93
+ setEnv({ NODE_ENV: 'development' })
94
+ clearCjs('../../src/config/load-env.js', 'dotenv')
95
+ vi.resetModules()
96
+
97
+ const dotenv = _require('dotenv')
98
+ const configSpy = vi.spyOn(dotenv, 'config').mockImplementation((opts) => {
99
+ if (opts.path.includes('.env.dev')) return { error: { code: 'ENOENT' } }
100
+ return { parsed: {} }
101
+ })
102
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
103
+
104
+ try {
105
+ const { loadEnv } = await import('../../src/config/load-env.js')
106
+ loadEnv()
107
+ expect(errorSpy).not.toHaveBeenCalled()
108
+ } finally {
109
+ configSpy.mockRestore()
110
+ errorSpy.mockRestore()
111
+ }
112
+ restore(s)
113
+ })
114
+
115
+ it('logs other dotenv errors', async () => {
116
+ const s = save('NODE_ENV')
117
+ setEnv({ NODE_ENV: 'development' })
118
+ clearCjs('../../src/config/load-env.js', 'dotenv')
119
+ vi.resetModules()
120
+
121
+ const dotenv = _require('dotenv')
122
+ const configSpy = vi.spyOn(dotenv, 'config').mockImplementation((opts) => {
123
+ if (opts.path.endsWith('.env')) return { error: new Error('bad syntax') }
124
+ return { parsed: {} }
125
+ })
126
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
127
+
128
+ try {
129
+ const { loadEnv } = await import('../../src/config/load-env.js')
130
+ loadEnv()
131
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('[dotenv]'), expect.stringContaining('bad syntax'))
132
+ } finally {
133
+ configSpy.mockRestore()
134
+ errorSpy.mockRestore()
135
+ }
136
+ restore(s)
137
+ })
138
+
139
+ it('falls back to development when NODE_ENV is unset', async () => {
140
+ const s = save('NODE_ENV')
141
+ delete process.env.NODE_ENV
142
+ clearCjs('../../src/config/load-env.js', 'dotenv')
143
+ vi.resetModules()
144
+
145
+ const dotenv = _require('dotenv')
146
+ const configSpy = vi.spyOn(dotenv, 'config').mockReturnValue({ parsed: {} })
147
+
148
+ try {
149
+ const { loadEnv } = await import('../../src/config/load-env.js')
150
+ loadEnv()
151
+
152
+ expect(configSpy).toHaveBeenCalledTimes(3)
153
+ const calls = configSpy.mock.calls.map(c => c[0].path)
154
+ expect(calls[0]).toContain('.env')
155
+ expect(calls[1]).toContain('.env.dev')
156
+ expect(calls[2]).toContain('.env.development')
157
+ } finally {
158
+ configSpy.mockRestore()
159
+ }
160
+ restore(s)
161
+ })
162
+
163
+ it('falls back to development env map for unknown NODE_ENV values', async () => {
164
+ const s = save('NODE_ENV')
165
+ setEnv({ NODE_ENV: 'staging' })
166
+ clearCjs('../../src/config/load-env.js', 'dotenv')
167
+ vi.resetModules()
168
+
169
+ const dotenv = _require('dotenv')
170
+ const configSpy = vi.spyOn(dotenv, 'config').mockReturnValue({ parsed: {} })
171
+
172
+ try {
173
+ const { loadEnv } = await import('../../src/config/load-env.js')
174
+ loadEnv()
175
+
176
+ expect(configSpy).toHaveBeenCalledTimes(3)
177
+ const calls = configSpy.mock.calls.map(c => c[0].path)
178
+ expect(calls[0]).toContain('.env')
179
+ expect(calls[1]).toContain('.env.dev')
180
+ expect(calls[2]).toContain('.env.development')
181
+ } finally {
182
+ configSpy.mockRestore()
183
+ }
184
+ restore(s)
185
+ })
186
+ })