TL;DR: Delete the settings file before starting the test.
Today I implemented a simple wrapper over the electron-settings functionality to gibe me access to a set of properties via get/set methods. My scenario is simple:
I have a property named
path.backup
and I want to be able toget
,set and
test it's set`.
The code is:
// paths.ts
const settings = require('electron-settings')
export class Paths {
public static readonly PATH_BACKUP_ID = 'path.backup'
getBackupPath(): string {
return settings.get(Paths.PATH_BACKUP_ID)
}
setBackupPath(newPath: string) {
return settings.set(Paths.PATH_BACKUP_ID, newPath)
}
hasBackupPath(): boolean {
const backup = settings.get(Paths.PATH_BACKUP_ID)
if (!backup) {
return false
}
return backup.length > 0
}
}
Now, my testing code would be something along the lines:
// paths.spec.ts
describe('Path settings', () => {
it('can process backup paths', () => {
let paths: Paths = new Paths()
expect(paths.getBackupPath()).toBe('')
path.setBackupPath('one')
expect(paths.getBackupPath()).toBe('one')
})
it('can detect it has source paths', () => {
let paths: Paths = new Paths()
expect(paths.hasBackupPath()).toBeFalsy()
paths.setSourcePaths('')
expect(paths.hasBackupPath()).toBeFalsy()
paths.setSourcePaths('one')
expect(paths.hasBackupPath()).toBeTruthy()
paths.setSourcePaths('')
expect(paths.hasBackupPath()).toBeFalsy()
})
})
And I was surprised to find the test failed in the second part (can detect it has source paths). Consistently.
Then, I was worried the tests would overwrite my own config file (fortunately it doesn't) and then it hit me: the settings file must be kept between the two tests, including the last value 'one'
for the backup path. The fact that I've initialised a new Paths()
object, it did not help at all! So, my solution is:
Delete the settings file at the beginning of each test:
// paths.spec.ts
// ...
const jetpack = require('fs-jetpack')
describe('Path settings', () => {
it('can process backup paths', () => {
// remove existing settings file
jetpack.remove(settings.file()) // <--- HERE!
let paths: Paths = new Paths()
expect(paths.getBackupPath()).toBe('')
path.setBackupPath('one')
expect(paths.getBackupPath()).toBe('one')
})
// ...
})
Member discussion: