Skip to content

feat: add tests for node/settings.ts #4717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions test/unit/node/settings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { logger } from "@coder/logger"
import { promises as fs } from "fs"
import path from "path"
import { SettingsProvider, CoderSettings } from "../../../src/node/settings"
import { clean, mockLogger, tmpdir } from "../../utils/helpers"

describe("settings", () => {
const testName = "settingsTests"
let testDir = ""

beforeAll(async () => {
mockLogger()
await clean(testName)
testDir = await tmpdir(testName)
})
describe("with invalid JSON in settings file", () => {
let mockSettingsFile = "coder.json"
let pathToMockSettingsFile = ""

beforeEach(async () => {
pathToMockSettingsFile = path.join(testDir, mockSettingsFile)
// Missing a quote, which makes it invalid intentionally
await fs.writeFile(pathToMockSettingsFile, '{"fakeKey":true,"helloWorld:"test"}')
})
afterEach(async () => {
jest.clearAllMocks()
})
it("should log a warning", async () => {
const settings = new SettingsProvider<CoderSettings>(pathToMockSettingsFile)
await settings.read()
// This happens when we can't parse a JSON (usually error in file)
expect(logger.warn).toHaveBeenCalledWith("Unexpected token t in JSON at position 29")
})
})
describe("with invalid settings file path", () => {
let mockSettingsFile = "nonExistent.json"
let pathToMockSettingsFile = ""

beforeEach(async () => {
// Add hello so it's a directory that doesn't exist
// NOTE: if we don't have that, it fails the test
// That's because it will write a file if it doesn't exist
// but it throws if there's a directory in the path that
// doesn't exist.
pathToMockSettingsFile = path.join(testDir, "hello", mockSettingsFile)
})
afterEach(async () => {
jest.clearAllMocks()
})
it("should log a warning", async () => {
const settings = new SettingsProvider<CoderSettings>(pathToMockSettingsFile)
await settings.write({
update: {
checked: 2,
version: "4.0.1",
},
})
// This happens if it tries to writeFile to a nonexistent path
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("ENOENT: no such file or directory"))
})
})
})