I have created a function that allows to manage caching. I use this function to cache the responses to API calls.
export const cache = async (key: string, callback: Function) => {
const cacheKey = `cache:${key}`;
const data = await useStorage().getItem(cacheKey);
if (data) {
console.log('Get cached data for key: %s', key);
return data;
}
const result = await callback();
console.log('Caching data for key: %s', key);
await useStorage().setItem(cacheKey, result);
return result;
}
Here is a use case:
import { cache } from '~/server/lib/caching/cache-manager';
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig();
const domain = event.context.params.domain;
const id = event.context.params.id;
const url = `${config.baseUrl}/api/${domain}/${id}`;
return await cache(url, () => {
return $fetch(url);
});
})
I would like to test the 'cache' function with vitest. For info, I added a vitest plugin to manage Nuxt aliases and auto-import, based on https://github.com/nuxt/framework/discussions/5379#discussioncomment-4224823
Here is the test, which does nothing, it just calls the 'cache' function:
import { describe, beforeEach, afterEach, test, expect, vi } from 'vitest'
import { cache } from '~/server/lib/caching/cache-manager'
describe('My test', () => {
test('my test', () => {
const result1 = cache('mykey', () => 3);
const result2 = cache('mykey', () => 3);
})
})
But I get an error when I call the cache function:
ReferenceError: useStorage is not defined
The Nitro's useStorage is not recognized.
I think the problem is related to #imports
which does not include server auto-imports.
I tested the following workaround but it still doesn't work:
https://github.com/nuxt/framework/issues/4290
You can test here:
https://stackblitz.com/edit/nuxt-starter-e3vtf2?file=tests%2Fserver%2Flib%2Fcaching%2Fcache-manager.test.ts
How can I test my 'cache' function that uses 'useStorage'?
I created a
storage.ts
file which contains theuseStorage
mock.I created an
index.ts
file that exports the mock.I declared the
index.ts
file in the vitest configuration in order to auto import the declared modules:If I need to auto import other mocks, I add them in
index.ts
.And I updated my test to test my
cache
function:You can test here:
https://stackblitz.com/edit/nuxt-starter-tl2ecc?file=tests/server/lib/caching/cache-manager.test.ts