Skip to content

Commit 09bb88f

Browse files
committed
test: test invalidate Cache
1 parent 0ace849 commit 09bb88f

2 files changed

Lines changed: 71 additions & 2 deletions

File tree

src/index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@ export class Pokedex {
6565
}
6666

6767
getCacheLength() {
68-
return sizeDB(this.config)
68+
return sizeCache(this.config)
6969
}
7070

7171
clearCache() {
72-
return clearDB(this.config)
72+
return clearCache(this.config)
7373
}
7474

7575
invalidateCache() {

test/test.html.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
376445
const button = document.getElementById('flush-cache-btn');
377446

378447
button.addEventListener('click', async () => {

0 commit comments

Comments
 (0)