Skip to content

Commit 70c91c8

Browse files
authored
feat: add tests for node/settings.ts (#4717)
1 parent 33c5097 commit 70c91c8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

test/unit/node/settings.test.ts

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

0 commit comments

Comments
 (0)