Skip to content

Commit 386bf29

Browse files
committed
feat: add tests for node/settings.ts
1 parent 33c5097 commit 386bf29

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

test/unit/node/settings.test.ts

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { logger } from "@coder/logger"
2+
import { promises as fs } from "fs"
3+
import { SettingsProvider, CoderSettings } from "../../../src/node/settings"
4+
import { clean, mockLogger, tmpdir } from "../../utils/helpers"
5+
6+
describe("settings", () => {
7+
describe("with invalid JSON in settings file", () => {
8+
const testName = "settingsInvalidJSON"
9+
let testDir = ""
10+
let mockSettingsFile = "coder.json"
11+
let pathToMockSettingsFile = ""
12+
13+
beforeEach(async () => {
14+
mockLogger()
15+
await clean(testName)
16+
testDir = await tmpdir(testName)
17+
pathToMockSettingsFile = `${testDir}/${mockSettingsFile}`
18+
// Missing a quote, which makes it invalid intentionally
19+
await fs.writeFile(pathToMockSettingsFile, '{"fakeKey":true,"helloWorld:"test"}')
20+
})
21+
afterEach(async () => {
22+
await fs.rm(testDir, { recursive: true, force: true })
23+
jest.clearAllMocks()
24+
})
25+
it("should log a warning", async () => {
26+
const settings = new SettingsProvider<CoderSettings>(pathToMockSettingsFile)
27+
await settings.read()
28+
// This happens when we can't parse a JSON (usually error in file)
29+
expect(logger.warn).toHaveBeenCalledWith("Unexpected token t in JSON at position 29")
30+
})
31+
})
32+
describe("with invalid settings file path", () => {
33+
const testName = "settingsInvalidPath"
34+
let testDir = ""
35+
let mockSettingsFile = "nonExistent.json"
36+
let pathToMockSettingsFile = ""
37+
38+
beforeEach(async () => {
39+
mockLogger()
40+
await clean(testName)
41+
testDir = await tmpdir(testName)
42+
// Add hello so it's a directory that doesn't exist
43+
// NOTE: if we don't have that, it fails the test
44+
// That's because it will write a file if it doesn't exist
45+
// but it throws if there's a directory in the path that
46+
// doesn't exist.
47+
pathToMockSettingsFile = `${testDir}/hello/${mockSettingsFile}`
48+
})
49+
afterEach(async () => {
50+
await fs.rm(testDir, { recursive: true, force: true })
51+
jest.clearAllMocks()
52+
})
53+
it("should log a warning", async () => {
54+
const settings = new SettingsProvider<CoderSettings>(pathToMockSettingsFile)
55+
await settings.write({
56+
update: {
57+
checked: 2,
58+
version: "4.0.1",
59+
},
60+
})
61+
// This happens if it tries to writeFile to a nonexistent path
62+
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("ENOENT: no such file or directory"))
63+
})
64+
})
65+
})

0 commit comments

Comments
 (0)