如何测试基于Nitro useStorage的Nuxt缓存函数?
解决Nuxt测试中useStorage未定义的问题
针对你在测试依赖Nitro useStorage的缓存函数时遇到的ReferenceError: useStorage is not defined错误,这里提供几种可行的解决方案:
1. 手动导入useStorage
在测试文件中直接从Nitro包导入useStorage,绕开自动导入的问题:
import { useStorage } from 'nitro' import { yourCacheFunction } from '@/utils/cache' test('测试缓存函数', async () => { const result = await yourCacheFunction('key') expect(result).toBeDefined() })
2. 模拟useStorage(推荐用于单元测试)
如果不需要依赖真实存储服务,用Vitest的mock功能模拟useStorage的行为,避免耦合Nitro环境:
import { vi } from 'vitest' import { yourCacheFunction } from '@/utils/cache' // 模拟nitro的useStorage vi.mock('nitro', () => ({ useStorage: vi.fn().mockReturnValue({ getItem: vi.fn().mockResolvedValue('mock-cached-data'), setItem: vi.fn().mockResolvedValue(undefined) }) })) test('缓存函数返回模拟数据', async () => { const data = await yourCacheFunction('test-key') expect(data).toBe('mock-cached-data') })
3. 调整Vitest配置启用服务端自动导入
修改vitest.config.ts,确保Nuxt插件加载服务端相关的自动导入和环境:
import { defineVitestConfig } from 'nuxt-vitest/config' export default defineVitestConfig({ test: { environment: 'nuxt', nuxt: { // 启用服务端环境支持 server: true, // 显式包含Nitro的自动导入 imports: { include: ['nitro/runtime/storage'] } } } })
4. 使用Nuxt官方测试工具链
如果需要测试真实的服务端行为,用@nuxt/test-utils搭建完整的服务端测试环境:
import { setup } from '@nuxt/test-utils/e2e' import { useStorage } from 'nitro' import { yourCacheFunction } from '@/utils/cache' await setup({ server: true, nitro: { // 配置内存存储作为测试用存储 storage: { default: { driver: 'memory' } } } }) test('缓存函数能正确读写存储', async () => { await yourCacheFunction('test-key', 'test-value') const cachedValue = await useStorage().getItem('test-key') expect(cachedValue).toBe('test-value') })
内容的提问来源于stack exchange,提问作者Nicolas Dos Santos
相关产品推荐
相关产品推荐

