From 7108c642f4ff6dc5f0c4d30b8a8960064ff8e90f Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Fri, 31 Dec 2021 01:52:28 +0100 Subject: test: Add tests for main package - Changed jest to run from the root package and reference the packages as projects. This required moving the base jest config file away from the project root. - Module isolation seems to prevent ts-jest from loading the shared package, so we disabled it for now. - To better facilitate mocking, services should be split into interfaces and implementation - Had to downgrade to chald 4.1.2 as per https://github.com/chalk/chalk/releases/tag/v5.0.0 at least until https://github.com/microsoft/TypeScript/issues/46452 is resolved. --- packages/main/esbuild.config.js | 5 +- packages/main/jest.config.js | 3 + packages/main/package.json | 3 +- packages/main/src/compositionRoot.ts | 4 +- .../main/src/controllers/__tests__/config.spec.ts | 184 +++++++++++++++++++++ .../src/controllers/__tests__/nativeTheme.spec.ts | 71 ++++++++ packages/main/src/controllers/config.ts | 16 +- .../main/src/services/ConfigPersistenceService.ts | 106 +----------- .../services/impl/ConfigPersistenceServiceImpl.ts | 128 ++++++++++++++ packages/main/src/utils/index.ts | 2 +- packages/main/src/utils/logging.ts | 16 +- packages/main/tsconfig.json | 1 + packages/preload/esbuild.config.js | 5 +- packages/preload/jest.config.js | 2 +- packages/preload/package.json | 3 +- .../__tests__/SophieRendererImpl.spec.ts | 36 ++-- packages/preload/tsconfig.json | 3 + packages/renderer/package.json | 2 +- packages/renderer/vite.config.js | 3 +- packages/service-inject/esbuild.config.js | 5 +- packages/service-preload/esbuild.config.js | 5 +- packages/service-shared/esbuild.config.js | 5 +- packages/shared/esbuild.config.js | 5 +- 23 files changed, 462 insertions(+), 151 deletions(-) create mode 100644 packages/main/jest.config.js create mode 100644 packages/main/src/controllers/__tests__/config.spec.ts create mode 100644 packages/main/src/controllers/__tests__/nativeTheme.spec.ts create mode 100644 packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts (limited to 'packages') diff --git a/packages/main/esbuild.config.js b/packages/main/esbuild.config.js index a39534d..af52f27 100644 --- a/packages/main/esbuild.config.js +++ b/packages/main/esbuild.config.js @@ -1,5 +1,6 @@ -import { node, fileURLToDirname } from '../../config/build-common.js'; -import { getConfig } from '../../config/esbuild-config.js'; +import { node } from '../../config/buildConstants.js'; +import { getConfig } from '../../config/esbuildConfig.js'; +import { fileURLToDirname } from '../../config/utils.js'; const externalPackages = ['electron']; diff --git a/packages/main/jest.config.js b/packages/main/jest.config.js new file mode 100644 index 0000000..b86463c --- /dev/null +++ b/packages/main/jest.config.js @@ -0,0 +1,3 @@ +import rootConfig from '../../config/jest.config.base.js'; + +export default rootConfig; diff --git a/packages/main/package.json b/packages/main/package.json index 99451bd..eb2ecf6 100644 --- a/packages/main/package.json +++ b/packages/main/package.json @@ -10,7 +10,7 @@ "dependencies": { "@sophie/service-shared": "workspace:*", "@sophie/shared": "workspace:*", - "chalk": "^5.0.0", + "chalk": "^4.1.2", "electron": "16.0.5", "json5": "^2.2.0", "lodash-es": "^4.17.21", @@ -27,6 +27,7 @@ "@types/node": "^17.0.5", "electron-devtools-installer": "^3.2.0", "esbuild": "^0.14.9", + "jest": "^27.4.5", "rimraf": "^3.0.2", "typescript": "^4.5.4" } diff --git a/packages/main/src/compositionRoot.ts b/packages/main/src/compositionRoot.ts index eb6f50f..d420bd6 100644 --- a/packages/main/src/compositionRoot.ts +++ b/packages/main/src/compositionRoot.ts @@ -22,12 +22,12 @@ import { app } from 'electron'; import { initConfig } from './controllers/config'; import { initNativeTheme } from './controllers/nativeTheme'; -import { ConfigPersistenceService } from './services/ConfigPersistenceService'; +import { ConfigPersistenceServiceImpl } from './services/impl/ConfigPersistenceServiceImpl'; import { MainStore } from './stores/MainStore'; import { Disposer } from './utils'; export async function init(store: MainStore): Promise { - const configPersistenceService = new ConfigPersistenceService(app.getPath('userData')); + const configPersistenceService = new ConfigPersistenceServiceImpl(app.getPath('userData')); const disposeConfigController = await initConfig(store.config, configPersistenceService); const disposeNativeThemeController = initNativeTheme(store); diff --git a/packages/main/src/controllers/__tests__/config.spec.ts b/packages/main/src/controllers/__tests__/config.spec.ts new file mode 100644 index 0000000..9471ca9 --- /dev/null +++ b/packages/main/src/controllers/__tests__/config.spec.ts @@ -0,0 +1,184 @@ +/* + * Copyright (C) 2021-2022 Kristóf Marussy + * + * This file is part of Sophie. + * + * Sophie is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { jest } from '@jest/globals'; +import { mocked } from 'jest-mock'; +import ms from 'ms'; + +import { initConfig } from '../config'; +import type { ConfigPersistenceService } from '../../services/ConfigPersistenceService'; +import { Config, config as configModel } from '../../stores/Config'; +import { Disposer, silenceLogger } from '../../utils'; + +let config: Config; +let persistenceService: ConfigPersistenceService = { + readConfig: jest.fn(), + writeConfig: jest.fn(), + watchConfig: jest.fn(), +}; +let lessThanThrottleMs = ms('0.1s'); +let throttleMs = ms('1s'); + +beforeAll(() => { + jest.useFakeTimers(); + silenceLogger(); +}); + +beforeEach(() => { + config = configModel.create(); +}); + +describe('when initializing', () => { + describe('when there is no config file', () => { + beforeEach(() => { + mocked(persistenceService.readConfig).mockResolvedValueOnce({ + found: false, + }); + }); + + it('should create a new config file', async () => { + await initConfig(config, persistenceService); + expect(persistenceService.writeConfig).toBeCalledTimes(1); + }); + + it('should bail if there is an an error creating the config file', async () => { + mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo')); + await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error); + }); + }); + + describe('when there is a valid config file', () => { + beforeEach(() => { + mocked(persistenceService.readConfig).mockResolvedValueOnce({ + found: true, + data: { + themeSource: 'dark', + }, + }); + }); + + it('should read the existing config file is there is one', async () => { + await initConfig(config, persistenceService); + expect(persistenceService.writeConfig).not.toBeCalled(); + expect(config.themeSource).toBe('dark'); + }); + + it('should bail if it cannot set up a watcher', async () => { + mocked(persistenceService.watchConfig).mockImplementationOnce(() => { + throw new Error('boo'); + }); + await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error); + }); + }); + + it('should not apply an invalid config file', async () => { + mocked(persistenceService.readConfig).mockResolvedValueOnce({ + found: true, + data: { + themeSource: -1, + }, + }); + await initConfig(config, persistenceService); + expect(config.themeSource).not.toBe(-1); + }); + + it('should bail if it cannot determine whether there is a config file', async () => { + mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo')); + await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error); + }); +}); + +describe('when it has loaded the config', () => { + let sutDisposer: Disposer; + let watcherDisposer: Disposer = jest.fn(); + let configChangedCallback: () => Promise; + + beforeEach(async () => { + mocked(persistenceService.readConfig).mockResolvedValueOnce({ + found: true, + data: {}, + }); + mocked(persistenceService.watchConfig).mockReturnValueOnce(watcherDisposer); + sutDisposer = await initConfig(config, persistenceService, throttleMs); + configChangedCallback = mocked(persistenceService.watchConfig).mock.calls[0][0]; + jest.resetAllMocks(); + }); + + it('should throttle saving changes to the config file', () => { + mocked(persistenceService.writeConfig).mockResolvedValue(undefined); + config.setThemeSource('dark'); + jest.advanceTimersByTime(lessThanThrottleMs); + config.setThemeSource('light'); + jest.advanceTimersByTime(throttleMs); + expect(persistenceService.writeConfig).toBeCalledTimes(1); + }); + + it('should handle config writing errors gracefully', () => { + mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo')); + config.setThemeSource('dark'); + jest.advanceTimersByTime(throttleMs); + expect(persistenceService.writeConfig).toBeCalledTimes(1); + }); + + it('should read the config file when it has changed', async () => { + mocked(persistenceService.readConfig).mockResolvedValueOnce({ + found: true, + data: { + themeSource: 'dark', + }, + }); + await configChangedCallback(); + // Do not write back the changes we have just read. + expect(persistenceService.writeConfig).not.toBeCalled(); + expect(config.themeSource).toBe('dark'); + }); + + it('should not apply an invalid config file when it has changed', async () => { + mocked(persistenceService.readConfig).mockResolvedValueOnce({ + found: true, + data: { + themeSource: -1, + }, + }); + await configChangedCallback(); + expect(config.themeSource).not.toBe(-1); + }); + + it('should handle config writing errors gracefully', async () => { + mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo')); + await configChangedCallback(); + }); + + describe('when it was disposed', () => { + beforeEach(() => { + sutDisposer(); + }); + + it('should dispose the watcher', () => { + expect(watcherDisposer).toBeCalled(); + }); + + it('should not listen to store changes any more', () => { + config.setThemeSource('dark'); + jest.advanceTimersByTime(2 * throttleMs); + expect(persistenceService.writeConfig).not.toBeCalled(); + }); + }); +}); diff --git a/packages/main/src/controllers/__tests__/nativeTheme.spec.ts b/packages/main/src/controllers/__tests__/nativeTheme.spec.ts new file mode 100644 index 0000000..cfb557c --- /dev/null +++ b/packages/main/src/controllers/__tests__/nativeTheme.spec.ts @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2021-2022 Kristóf Marussy + * + * This file is part of Sophie. + * + * Sophie is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { jest } from '@jest/globals'; +import { mocked } from 'jest-mock'; + +import { createMainStore, MainStore } from '../../stores/MainStore'; +import { Disposer } from '../../utils'; + +let shouldUseDarkColors = false; + +jest.unstable_mockModule('electron', () => ({ + nativeTheme: { + themeSource: 'system', + get shouldUseDarkColors() { + return shouldUseDarkColors; + }, + on: jest.fn(), + off: jest.fn(), + }, +})); + +const { nativeTheme } = await import('electron'); +const { initNativeTheme } = await import('../nativeTheme'); + +let store: MainStore; +let disposeSut: Disposer; + +beforeEach(() => { + store = createMainStore(); + disposeSut = initNativeTheme(store); +}); + +it('should register a nativeTheme updated listener', () => { + expect(nativeTheme.on).toBeCalledWith('updated', expect.anything()); +}); + +it('should synchronize themeSource changes to the nativeTheme', () => { + store.config.setThemeSource('dark'); + expect(nativeTheme.themeSource).toBe('dark'); +}); + +it('should synchronize shouldUseDarkColors changes to the store', () => { + const listener = mocked(nativeTheme.on).mock.calls.find(([event]) => event === 'updated')![1]; + shouldUseDarkColors = true; + listener(); + expect(store.shared.shouldUseDarkColors).toBe(true); +}); + +it('should remove the listener on dispose', () => { + const listener = mocked(nativeTheme.on).mock.calls.find(([event]) => event === 'updated')![1]; + disposeSut(); + expect(nativeTheme.off).toBeCalledWith('updated', listener); +}); diff --git a/packages/main/src/controllers/config.ts b/packages/main/src/controllers/config.ts index 600a142..d3559c8 100644 --- a/packages/main/src/controllers/config.ts +++ b/packages/main/src/controllers/config.ts @@ -60,12 +60,8 @@ export async function initConfig( if (!await readConfig()) { log.info('Config file was not found'); - try { - await writeConfig(); - log.info('Created config file'); - } catch (err) { - log.error('Failed to initialize config', err); - } + await writeConfig(); + log.info('Created config file'); } const disposeOnSnapshot = onSnapshot(config, debounce((snapshot) => { @@ -73,12 +69,16 @@ export async function initConfig( if (lastSnapshotOnDisk !== snapshot) { writeConfig().catch((err) => { log.error('Failed to write config on config change', err); - }) + }); } }, debounceTime)); const disposeWatcher = persistenceService.watchConfig(async () => { - await readConfig(); + try { + await readConfig(); + } catch (err) { + log.error('Failed to read config', err); + } }, debounceTime); return () => { diff --git a/packages/main/src/services/ConfigPersistenceService.ts b/packages/main/src/services/ConfigPersistenceService.ts index b2109f6..b3ad162 100644 --- a/packages/main/src/services/ConfigPersistenceService.ts +++ b/packages/main/src/services/ConfigPersistenceService.ts @@ -17,112 +17,16 @@ * * SPDX-License-Identifier: AGPL-3.0-only */ -import { watch } from 'fs'; -import { readFile, stat, writeFile } from 'fs/promises'; -import JSON5 from 'json5'; -import throttle from 'lodash-es/throttle'; -import { join } from 'path'; import type { ConfigSnapshotOut } from '../stores/Config'; -import { Disposer, getLogger } from '../utils'; - -const log = getLogger('configPersistence'); +import { Disposer } from '../utils'; export type ReadConfigResult = { found: true; data: unknown; } | { found: false; }; -export class ConfigPersistenceService { - private readonly configFilePath: string; - - private writingConfig = false; - - private timeLastWritten: Date | null = null; - - constructor( - private readonly userDataDir: string, - private readonly configFileName: string = 'config.json5', - ) { - this.configFileName = configFileName; - this.configFilePath = join(this.userDataDir, this.configFileName); - } - - async readConfig(): Promise { - let configStr; - try { - configStr = await readFile(this.configFilePath, 'utf8'); - } catch (err) { - if ((err as NodeJS.ErrnoException).code === 'ENOENT') { - log.debug('Config file', this.configFilePath, 'was not found'); - return { found: false }; - } - throw err; - } - log.info('Read config file', this.configFilePath); - return { - found: true, - data: JSON5.parse(configStr), - }; - } - - async writeConfig(configSnapshot: ConfigSnapshotOut): Promise { - const configJson = JSON5.stringify(configSnapshot, { - space: 2, - }); - this.writingConfig = true; - try { - await writeFile(this.configFilePath, configJson, 'utf8'); - const { mtime } = await stat(this.configFilePath); - log.trace('Config file', this.configFilePath, 'last written at', mtime); - this.timeLastWritten = mtime; - } finally { - this.writingConfig = false; - } - log.info('Wrote config file', this.configFilePath); - } - - watchConfig(callback: () => Promise, throttleMs: number): Disposer { - log.debug('Installing watcher for', this.userDataDir); - - const configChanged = throttle(async () => { - let mtime: Date; - try { - const stats = await stat(this.configFilePath); - mtime = stats.mtime; - log.trace('Config file last modified at', mtime); - } catch (err) { - if ((err as NodeJS.ErrnoException).code === 'ENOENT') { - log.debug('Config file', this.configFilePath, 'was deleted after being changed'); - return; - } - throw err; - } - if (!this.writingConfig - && (this.timeLastWritten === null || mtime > this.timeLastWritten)) { - log.debug( - 'Found a config file modified at', - mtime, - 'whish is newer than last written', - this.timeLastWritten, - ); - return callback(); - } - }, throttleMs); - - const watcher = watch(this.userDataDir, { - persistent: false, - }); +export interface ConfigPersistenceService { + readConfig(): Promise; - watcher.on('change', (eventType, filename) => { - if (eventType === 'change' - && (filename === this.configFileName || filename === null)) { - configChanged()?.catch((err) => { - console.log('Unhandled error while listening for config changes', err); - }); - } - }); + writeConfig(configSnapshot: ConfigSnapshotOut): Promise; - return () => { - log.trace('Removing watcher for', this.configFilePath); - watcher.close(); - }; - } + watchConfig(callback: () => Promise, throttleMs: number): Disposer; } diff --git a/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts b/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts new file mode 100644 index 0000000..bffc38c --- /dev/null +++ b/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts @@ -0,0 +1,128 @@ + +/* + * Copyright (C) 2021-2022 Kristóf Marussy + * + * This file is part of Sophie. + * + * Sophie is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-only + */ +import { watch } from 'fs'; +import { readFile, stat, writeFile } from 'fs/promises'; +import JSON5 from 'json5'; +import throttle from 'lodash-es/throttle'; +import { join } from 'path'; + +import type { ConfigPersistenceService, ReadConfigResult } from '../ConfigPersistenceService'; +import type { ConfigSnapshotOut } from '../../stores/Config'; +import { Disposer, getLogger } from '../../utils'; + +const log = getLogger('configPersistence'); + +export class ConfigPersistenceServiceImpl implements ConfigPersistenceService { + private readonly configFilePath: string; + + private writingConfig = false; + + private timeLastWritten: Date | null = null; + + constructor( + private readonly userDataDir: string, + private readonly configFileName: string = 'config.json5', + ) { + this.configFileName = configFileName; + this.configFilePath = join(this.userDataDir, this.configFileName); + } + + async readConfig(): Promise { + let configStr; + try { + configStr = await readFile(this.configFilePath, 'utf8'); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') { + log.debug('Config file', this.configFilePath, 'was not found'); + return { found: false }; + } + throw err; + } + log.info('Read config file', this.configFilePath); + return { + found: true, + data: JSON5.parse(configStr), + }; + } + + async writeConfig(configSnapshot: ConfigSnapshotOut): Promise { + const configJson = JSON5.stringify(configSnapshot, { + space: 2, + }); + this.writingConfig = true; + try { + await writeFile(this.configFilePath, configJson, 'utf8'); + const { mtime } = await stat(this.configFilePath); + log.trace('Config file', this.configFilePath, 'last written at', mtime); + this.timeLastWritten = mtime; + } finally { + this.writingConfig = false; + } + log.info('Wrote config file', this.configFilePath); + } + + watchConfig(callback: () => Promise, throttleMs: number): Disposer { + log.debug('Installing watcher for', this.userDataDir); + + const configChanged = throttle(async () => { + let mtime: Date; + try { + const stats = await stat(this.configFilePath); + mtime = stats.mtime; + log.trace('Config file last modified at', mtime); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') { + log.debug('Config file', this.configFilePath, 'was deleted after being changed'); + return; + } + throw err; + } + if (!this.writingConfig + && (this.timeLastWritten === null || mtime > this.timeLastWritten)) { + log.debug( + 'Found a config file modified at', + mtime, + 'whish is newer than last written', + this.timeLastWritten, + ); + return callback(); + } + }, throttleMs); + + const watcher = watch(this.userDataDir, { + persistent: false, + }); + + watcher.on('change', (eventType, filename) => { + if (eventType === 'change' + && (filename === this.configFileName || filename === null)) { + configChanged()?.catch((err) => { + console.log('Unhandled error while listening for config changes', err); + }); + } + }); + + return () => { + log.trace('Removing watcher for', this.configFilePath); + watcher.close(); + }; + } +} diff --git a/packages/main/src/utils/index.ts b/packages/main/src/utils/index.ts index 9a57e02..2b85989 100644 --- a/packages/main/src/utils/index.ts +++ b/packages/main/src/utils/index.ts @@ -22,4 +22,4 @@ import { IDisposer } from 'mobx-state-tree'; export type Disposer = IDisposer; -export { getLogger } from './logging'; +export { getLogger, silenceLogger } from './logging'; diff --git a/packages/main/src/utils/logging.ts b/packages/main/src/utils/logging.ts index 6c4cba2..ed40365 100644 --- a/packages/main/src/utils/logging.ts +++ b/packages/main/src/utils/logging.ts @@ -18,17 +18,17 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import chalk, { ChalkInstance } from 'chalk'; +import chalk, { Chalk } from 'chalk'; import loglevel, { Logger } from 'loglevel'; import prefix from 'loglevel-plugin-prefix'; -if (import.meta.env.DEV) { +if (import.meta.env?.DEV) { loglevel.setLevel('debug'); } else { loglevel.setLevel('info'); } -const COLORS: Partial> = { +const COLORS: Partial> = { TRACE: chalk.magenta, DEBUG: chalk.cyan, INFO: chalk.blue, @@ -37,7 +37,7 @@ const COLORS: Partial> = { CRITICAL: chalk.red, }; -function getColor(level: string): ChalkInstance { +function getColor(level: string): Chalk { return COLORS[level] ?? chalk.gray; } @@ -52,3 +52,11 @@ prefix.apply(loglevel, { export function getLogger(loggerName: string): Logger { return loglevel.getLogger(loggerName); } + +export function silenceLogger(): void { + loglevel.disableAll(); + const loggers = loglevel.getLoggers(); + for (const loggerName of Object.keys(loggers)) { + loggers[loggerName].disableAll(); + } +} diff --git a/packages/main/tsconfig.json b/packages/main/tsconfig.json index 10f5765..1401445 100644 --- a/packages/main/tsconfig.json +++ b/packages/main/tsconfig.json @@ -3,6 +3,7 @@ "compilerOptions": { "noEmit": true, "types": [ + "@types/jest", "node" ] }, diff --git a/packages/preload/esbuild.config.js b/packages/preload/esbuild.config.js index de51fc5..b73a071 100644 --- a/packages/preload/esbuild.config.js +++ b/packages/preload/esbuild.config.js @@ -1,5 +1,6 @@ -import { chrome, fileURLToDirname } from '../../config/build-common.js'; -import { getConfig } from '../../config/esbuild-config.js'; +import { chrome } from '../../config/buildConstants.js'; +import { getConfig } from '../../config/esbuildConfig.js'; +import { fileURLToDirname } from '../../config/utils.js'; export default getConfig({ absWorkingDir: fileURLToDirname(import.meta.url), diff --git a/packages/preload/jest.config.js b/packages/preload/jest.config.js index faecf9a..e474c4c 100644 --- a/packages/preload/jest.config.js +++ b/packages/preload/jest.config.js @@ -1,4 +1,4 @@ -import rootConfig from '../../jest.config.js'; +import rootConfig from '../../config/jest.config.base.js'; /** @type {import('ts-jest').InitialOptionsTsJest} */ export default { diff --git a/packages/preload/package.json b/packages/preload/package.json index e6dd0ee..9818ba8 100644 --- a/packages/preload/package.json +++ b/packages/preload/package.json @@ -6,7 +6,6 @@ "type": "module", "types": "dist-types/index.d.ts", "scripts": { - "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js", "typecheck": "tsc" }, "dependencies": { @@ -16,7 +15,7 @@ "mobx-state-tree": "^5.1.0" }, "devDependencies": { - "@types/jest": "^27.0.3", + "@types/jest": "^27.4.0", "jest": "^27.4.5", "jest-mock": "^27.4.2", "jsdom": "^19.0.0", diff --git a/packages/preload/src/contextBridge/__tests__/SophieRendererImpl.spec.ts b/packages/preload/src/contextBridge/__tests__/SophieRendererImpl.spec.ts index 41937c2..fdd1cc5 100644 --- a/packages/preload/src/contextBridge/__tests__/SophieRendererImpl.spec.ts +++ b/packages/preload/src/contextBridge/__tests__/SophieRendererImpl.spec.ts @@ -18,7 +18,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { describe, it, jest } from '@jest/globals'; +import { jest } from '@jest/globals'; import { mocked } from 'jest-mock'; import log from 'loglevel'; import type { IJsonPatch } from 'mobx-state-tree'; @@ -67,7 +67,9 @@ const invalidAction = { action: 'not-a-valid-action', } as unknown as Action; -log.disableAll(); +beforeAll(() => { + log.disableAll(); +}); describe('createSophieRenderer', () => { it('registers a shared store patch listener', () => { @@ -95,59 +97,59 @@ describe('SophieRendererImpl', () => { }); describe('onSharedStoreChange', () => { - it('requests a snapshot from the main process', async () => { + it('should request a snapshot from the main process', async () => { mocked(ipcRenderer.invoke).mockResolvedValueOnce(snapshot); await sut.onSharedStoreChange(listener); expect(ipcRenderer.invoke).toBeCalledWith(RendererToMainIpcMessage.GetSharedStoreSnapshot); expect(listener.onSnapshot).toBeCalledWith(snapshot); }); - it('catches IPC errors without exposing them', async () => { + it('should catch IPC errors without exposing them', async () => { mocked(ipcRenderer.invoke).mockRejectedValue(new Error('s3cr3t')); await expect(sut.onSharedStoreChange(listener)).rejects.not.toHaveProperty( 'message', expect.stringMatching(/s3cr3t/), ); - expect(listener.onSnapshot).toBeCalledTimes(0); + expect(listener.onSnapshot).not.toBeCalled(); }); - it('does not pass on invalid snapshots', async () => { + it('should not pass on invalid snapshots', async () => { mocked(ipcRenderer.invoke).mockResolvedValueOnce(invalidSnapshot); await expect(sut.onSharedStoreChange(listener)).rejects.toBeInstanceOf(Error); - expect(listener.onSnapshot).toBeCalledTimes(0); + expect(listener.onSnapshot).not.toBeCalled(); }); }); describe('dispatchAction', () => { - it('dispatched valid actions', () => { + it('should dispatch valid actions', () => { sut.dispatchAction(action); expect(ipcRenderer.send).toBeCalledWith(RendererToMainIpcMessage.DispatchAction, action); }); - it('does not dispatch invalid actions', () => { + it('should not dispatch invalid actions', () => { expect(() => sut.dispatchAction(invalidAction)).toThrowError(); - expect(ipcRenderer.send).toBeCalledTimes(0); + expect(ipcRenderer.send).not.toBeCalled(); }); }); describe('when no listener is registered', () => { - it('discards the received patch without any error', () => { + it('should discard the received patch without any error', () => { onSharedStorePatch(event, patch); }); }); function itRefusesToRegisterAnotherListener() { - it('refuses to register another listener', async () => { + it('should refuse to register another listener', async () => { await expect(sut.onSharedStoreChange(listener)).rejects.toBeInstanceOf(Error); }); } function itDoesNotPassPatchesToTheListener( - name: string = 'does not pass patches to the listener', + name: string = 'should not pass patches to the listener', ) { it(name, () => { onSharedStorePatch(event, patch); - expect(listener.onPatch).toBeCalledTimes(0); + expect(listener.onPatch).not.toBeCalled(); }); } @@ -157,12 +159,12 @@ describe('SophieRendererImpl', () => { await sut.onSharedStoreChange(listener); }); - it('passes patches to the listener', () => { + it('should pass patches to the listener', () => { onSharedStorePatch(event, patch); expect(listener.onPatch).toBeCalledWith(patch); }); - it('catches listener errors', () => { + it('should catch listener errors', () => { mocked(listener.onPatch).mockImplementation(() => { throw new Error(); }); onSharedStorePatch(event, patch); }); @@ -176,7 +178,7 @@ describe('SophieRendererImpl', () => { listener.onPatch.mockRestore(); }); - itDoesNotPassPatchesToTheListener('does not pass on patches any more'); + itDoesNotPassPatchesToTheListener('should not pass on patches any more'); }); }); diff --git a/packages/preload/tsconfig.json b/packages/preload/tsconfig.json index 0f27305..741d435 100644 --- a/packages/preload/tsconfig.json +++ b/packages/preload/tsconfig.json @@ -6,6 +6,9 @@ "dom", "dom.iterable", "esnext" + ], + "types": [ + "@types/jest" ] }, "references": [ diff --git a/packages/renderer/package.json b/packages/renderer/package.json index 2a26b2b..0a9f4ef 100644 --- a/packages/renderer/package.json +++ b/packages/renderer/package.json @@ -30,6 +30,6 @@ "remotedev": "^0.2.9", "rimraf": "^3.0.2", "typescript": "^4.5.4", - "vite": "^2.7.9" + "vite": "^2.7.10" } } diff --git a/packages/renderer/vite.config.js b/packages/renderer/vite.config.js index 6f3d351..82ce33d 100644 --- a/packages/renderer/vite.config.js +++ b/packages/renderer/vite.config.js @@ -4,7 +4,8 @@ import { builtinModules } from 'module'; import { join } from 'path'; import react from '@vitejs/plugin-react'; -import { banner, chrome, fileURLToDirname } from '../../config/build-common.js'; +import { banner, chrome } from '../../config/buildConstants.js'; +import { fileURLToDirname } from '../../config/utils.js'; const thisDir = fileURLToDirname(import.meta.url); diff --git a/packages/service-inject/esbuild.config.js b/packages/service-inject/esbuild.config.js index 3f1d6d0..2169c8e 100644 --- a/packages/service-inject/esbuild.config.js +++ b/packages/service-inject/esbuild.config.js @@ -1,5 +1,6 @@ -import { chrome, fileURLToDirname } from '../../config/build-common.js'; -import { getConfig } from '../../config/esbuild-config.js'; +import { chrome } from '../../config/buildConstants.js'; +import { getConfig } from '../../config/esbuildConfig.js'; +import { fileURLToDirname } from '../../config/utils.js'; export default getConfig({ absWorkingDir: fileURLToDirname(import.meta.url), diff --git a/packages/service-preload/esbuild.config.js b/packages/service-preload/esbuild.config.js index 3c67b31..b73a071 100644 --- a/packages/service-preload/esbuild.config.js +++ b/packages/service-preload/esbuild.config.js @@ -1,5 +1,6 @@ -import { chrome, fileURLToDirname } from "../../config/build-common.js"; -import { getConfig } from '../../config/esbuild-config.js'; +import { chrome } from '../../config/buildConstants.js'; +import { getConfig } from '../../config/esbuildConfig.js'; +import { fileURLToDirname } from '../../config/utils.js'; export default getConfig({ absWorkingDir: fileURLToDirname(import.meta.url), diff --git a/packages/service-shared/esbuild.config.js b/packages/service-shared/esbuild.config.js index 8df2edf..071ca7d 100644 --- a/packages/service-shared/esbuild.config.js +++ b/packages/service-shared/esbuild.config.js @@ -1,5 +1,6 @@ -import { chrome, fileURLToDirname } from '../../config/build-common.js'; -import { getConfig } from '../../config/esbuild-config.js'; +import { chrome } from '../../config/buildConstants.js'; +import { getConfig } from '../../config/esbuildConfig.js'; +import { fileURLToDirname } from '../../config/utils.js'; export default getConfig({ absWorkingDir: fileURLToDirname(import.meta.url), diff --git a/packages/shared/esbuild.config.js b/packages/shared/esbuild.config.js index fbaa6f1..b134931 100644 --- a/packages/shared/esbuild.config.js +++ b/packages/shared/esbuild.config.js @@ -1,5 +1,6 @@ -import { chrome, fileURLToDirname } from '../../config/build-common.js'; -import { getConfig } from '../../config/esbuild-config.js'; +import { chrome } from '../../config/buildConstants.js'; +import { getConfig } from '../../config/esbuildConfig.js'; +import { fileURLToDirname } from '../../config/utils.js'; export default getConfig({ absWorkingDir: fileURLToDirname(import.meta.url), -- cgit v1.2.3-54-g00ecf