github.com/derat/nup@v0.0.0-20230418113745-15592ba7c620/test/web/unit/config.test.js (about) 1 // Copyright 2021 Daniel Erat. 2 // All rights reserved. 3 4 import { 5 afterEach, 6 beforeEach, 7 expectEq, 8 expectThrows, 9 suite, 10 test, 11 } from './test.js'; 12 import MockWindow from './mock-window.js'; 13 import { Config, ConfigKey, GainType, Pref, Theme } from './config.js'; 14 15 suite('config', () => { 16 let w = null; 17 beforeEach(() => { 18 w = new MockWindow(); 19 }); 20 afterEach(() => { 21 w.finish(); 22 }); 23 24 test('saveAndReload', () => { 25 let cfg = new Config(); 26 cfg.set(Pref.THEME, Theme.DARK); 27 cfg.set(Pref.GAIN_TYPE, GainType.NONE); 28 cfg.set(Pref.PRE_AMP, 0.3); 29 cfg.save(); 30 31 cfg = new Config(); 32 expectEq(cfg.get(Pref.THEME), Theme.DARK, 'Theme'); 33 expectEq(cfg.get(Pref.GAIN_TYPE), GainType.NONE, 'GainType'); 34 expectEq(cfg.get(Pref.PRE_AMP), 0.3, 'PreAmp'); 35 }); 36 37 test('ignoreInvalidConfig', () => { 38 window.localStorage.setItem(ConfigKey, 'not json'); 39 40 // These match the defaults from the c'tor. 41 const cfg = new Config(); 42 expectEq(cfg.get(Pref.THEME), Theme.AUTO); 43 expectEq(cfg.get(Pref.GAIN_TYPE), GainType.AUTO); 44 expectEq(cfg.get(Pref.PRE_AMP), 0); 45 }); 46 47 test('skipInvalidPrefs', () => { 48 // This matches #load(). 49 window.localStorage.setItem( 50 ConfigKey, 51 JSON.stringify({ 52 bogus: 2.3, 53 [Pref.THEME]: Theme.DARK, 54 }) 55 ); 56 57 // We should still load the valid theme pref. 58 const cfg = new Config(); 59 expectEq(cfg.get(Pref.THEME), Theme.DARK); 60 }); 61 62 test('addCallback', () => { 63 const cfg = new Config(); 64 const seen = []; // [name, value] pairs 65 cfg.addCallback((n, v) => seen.push([n, v])); 66 67 cfg.set(Pref.THEME, Theme.DARK); 68 cfg.set(Pref.GAIN_TYPE, GainType.NONE); 69 cfg.set(Pref.PRE_AMP, 0.3); 70 expectEq(seen, [ 71 [Pref.THEME, Theme.DARK], 72 [Pref.GAIN_TYPE, GainType.NONE], 73 [Pref.PRE_AMP, 0.3], 74 ]); 75 }); 76 77 test('invalid', () => { 78 const cfg = new Config(); 79 cfg.set(Pref.THEME, Theme.DARK); 80 cfg.set(Pref.PRE_AMP, 0.3); 81 82 expectThrows(() => cfg.set(Pref.THEME, 'abc'), 'Setting int to string'); 83 expectThrows(() => cfg.set(Pref.THEME, null), 'Setting int to null'); 84 expectThrows( 85 () => cfg.set(Pref.THEME, undefined), 86 'Setting int to undefined' 87 ); 88 89 expectThrows(() => cfg.set(Pref.PRE_AMP, 'abc'), 'Setting float to string'); 90 expectThrows(() => cfg.set(Pref.PRE_AMP, null), 'Setting float to null'); 91 expectThrows( 92 () => cfg.set(Pref.PRE_AMP, undefined), 93 'Setting float to undefined' 94 ); 95 96 expectThrows(() => cfg.get('bogus'), 'Getting unknown pref'); 97 expectThrows(() => cfg.set('bogus', 2), 'Setting unknown pref'); 98 99 // The original values should be retained. 100 expectEq(cfg.get(Pref.THEME), Theme.DARK); 101 expectEq(cfg.get(Pref.PRE_AMP), 0.3); 102 }); 103 });