@@ -373,6 +373,75 @@ describe("pokedex", function () {
373373 } ) ;
374374} ) ;
375375
376+ describe ( "Cache" , function ( ) {
377+ this . timeout ( 10000 ) ;
378+ const originalFetch = window . fetch ;
379+ let P ;
380+ let fetchCalls = [ ] ;
381+
382+ before ( async function ( ) {
383+ P = await Pokedex . init ( { cache : true } ) ;
384+ window . fetch = async ( url ) => {
385+ const url_str = url . toString ( ) ;
386+ fetchCalls . push ( url_str ) ;
387+
388+ if ( url_str . includes ( '/pokemon/ditto' ) ) {
389+ return new Response ( JSON . stringify ( { name : 'ditto' } ) , {
390+ headers : { 'X-PokeAPI-Deploy-Date' : '100' }
391+ } ) ;
392+ }
393+ if ( url_str . includes ( '/pokemon/pikachu' ) ) {
394+ return new Response ( JSON . stringify ( { name : 'pikachu' } ) , {
395+ headers : { 'X-PokeAPI-Deploy-Date' : '300' }
396+ } ) ;
397+ }
398+ if ( url_str . includes ( '/meta' ) ) {
399+ return new Response ( JSON . stringify ( { deploy_date : '200' } ) ) ;
400+ }
401+ return originalFetch ( url ) ;
402+ } ;
403+ } ) ;
404+
405+ beforeEach ( async function ( ) {
406+ await P . clearCache ( ) ;
407+ fetchCalls = [ ] ;
408+ } ) ;
409+
410+ after ( function ( ) {
411+ window . fetch = originalFetch ;
412+ } ) ;
413+
414+ it ( "should invalidate old cache entries and keep new ones" , async function ( ) {
415+ await P . getPokemonByName ( 'ditto' ) ;
416+ await P . getPokemonByName ( 'pikachu' ) ;
417+ expect ( fetchCalls . length ) . to . equal ( 2 ) ;
418+
419+ let cacheSize = await P . getCacheLength ( ) ;
420+ expect ( cacheSize ) . to . equal ( 2 ) ;
421+
422+ fetchCalls = [ ] ;
423+ await P . getPokemonByName ( 'ditto' ) ;
424+ await P . getPokemonByName ( 'pikachu' ) ;
425+ expect ( fetchCalls . length ) . to . equal ( 0 ) ;
426+
427+ await P . invalidateCache ( ) ;
428+ expect ( fetchCalls . length ) . to . equal ( 1 ) ;
429+ expect ( fetchCalls [ 0 ] ) . to . include ( '/meta' ) ;
430+
431+ cacheSize = await P . getCacheLength ( ) ;
432+ expect ( cacheSize ) . to . equal ( 1 ) ;
433+
434+ fetchCalls = [ ] ;
435+ await P . getPokemonByName ( 'ditto' ) ;
436+ await P . getPokemonByName ( 'pikachu' ) ;
437+ expect ( fetchCalls . length ) . to . equal ( 1 ) ;
438+ expect ( fetchCalls [ 0 ] ) . to . include ( '/pokemon/ditto' ) ;
439+
440+ cacheSize = await P . getCacheLength ( ) ;
441+ expect ( cacheSize ) . to . equal ( 2 ) ;
442+ } ) ;
443+ } ) ;
444+
376445const button = document . getElementById ( 'flush-cache-btn' ) ;
377446
378447button . addEventListener ( 'click' , async ( ) => {
0 commit comments