22 * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
33 * SPDX-License-Identifier: GPL-3.0-or-later
44 */
5- import { expect , test } from 'vitest'
5+ import { expect , test , vi } from 'vitest'
66import { loadState } from '../lib'
77
8+ function appendInput ( app : string , key : string , value : string ) {
9+ const input = document . createElement ( 'input' )
10+ input . setAttribute ( 'type' , 'hidden' )
11+ input . setAttribute ( 'id' , `initial-state-${ app } -${ key } ` )
12+ input . setAttribute ( 'value' , btoa ( JSON . stringify ( value ) ) )
13+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
14+ document . querySelector ( 'body' ) ! . appendChild ( input )
15+ }
16+
817test ( 'throw if nothing found' , ( ) => {
918 expect ( ( ) => loadState ( 'test' , 'key' ) ) . toThrow ( new Error ( 'Could not find initial state key of test' ) )
1019} )
@@ -14,14 +23,21 @@ test('return default if provided', () => {
1423} )
1524
1625test ( 'find correct value' , ( ) => {
17- const input = document . createElement ( 'input' )
18- input . setAttribute ( 'type' , 'hidden' )
19- input . setAttribute ( 'id' , 'initial-state-test-key' )
20- input . setAttribute ( 'value' , btoa ( JSON . stringify ( 'foo' ) ) )
21- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
22- document . querySelector ( 'body' ) ! . appendChild ( input )
26+ appendInput ( 'test' , 'key' , 'foo' )
2327
2428 const state = loadState ( 'test' , 'key' )
2529
2630 expect ( state ) . toBe ( 'foo' )
2731} )
32+
33+ test ( 'returns cached value with consequent calls' , ( ) => {
34+ vi . spyOn ( JSON , 'parse' )
35+
36+ appendInput ( 'test' , 'cachedKey' , 'foo' )
37+
38+ for ( let i = 0 ; i < 10 ; i ++ ) {
39+ loadState ( 'test' , 'cachedKey' )
40+ }
41+
42+ expect ( JSON . parse ) . toHaveBeenCalledTimes ( 1 )
43+ } )
0 commit comments