Nuxt 3自定义apiFetch插件的Jest单元测试实现求助
Nuxt3 API插件Jest单元测试方案
错误原因
useNuxtApp是Nuxt3专属的组合式API,依赖Nuxt上下文环境才能运行。直接在Jest中调用会因为缺少上下文抛出TypeError: useNuxtApp is not a function,必须通过Mock相关API来模拟Nuxt运行环境。
测试思路
- Mock Nuxt核心API(
useRuntimeConfig、defineNuxtPlugin、useNuxtApp),模拟插件运行所需的上下文 - Mock
ohmyfetch的$fetch.create方法,追踪其调用参数和返回的请求函数 - 执行插件逻辑,验证配置读取、方法注入、请求拼接是否符合预期
完整测试代码
第一步:Mock依赖模块
import { defineNuxtPlugin, useRuntimeConfig, useNuxtApp } from '#app' import { $fetch } from 'ohmyfetch' // 替换为你的插件实际路径 import apiPlugin from '@/plugins/api' // Mock Nuxt 核心API jest.mock('#app', () => ({ defineNuxtPlugin: jest.fn((pluginFn) => pluginFn), useRuntimeConfig: jest.fn(), useNuxtApp: jest.fn(() => ({ provide: jest.fn() })) })) // Mock ohmyfetch 的$fetch.create方法 jest.mock('ohmyfetch', () => ({ $fetch: { create: jest.fn(() => jest.fn()) } }))
第二步:编写测试用例
测试1:验证插件正确读取配置并注入apiFetch
it('injects apiFetch with baseURL from runtime config', () => { // 模拟runtimeConfig返回的BASE_URL const mockBaseUrl = 'https://api.example.com' useRuntimeConfig.mockReturnValue({ BASE_URL: mockBaseUrl }) // 执行插件逻辑 apiPlugin() // 验证$fetch.create是否使用正确的baseURL初始化 expect($fetch.create).toHaveBeenCalledWith({ baseURL: mockBaseUrl }) // 验证插件是否正确向NuxtApp注入apiFetch方法 const nuxtApp = useNuxtApp() expect(nuxtApp.provide).toHaveBeenCalledWith('apiFetch', expect.any(Function)) })
测试2:验证apiFetch请求时正确拼接URL并返回结果
it('apiFetch requests use correct full URL and returns mock data', async () => { const mockBaseUrl = 'https://api.example.com' const mockEndpoint = '/api/prints' const mockResponse = [{ id: 1, title: 'Test Print' }] // 模拟runtimeConfig useRuntimeConfig.mockReturnValue({ BASE_URL: mockBaseUrl }) // 模拟$fetch.create返回的请求函数,预设返回值 const mockFetchFn = jest.fn().mockResolvedValue(mockResponse) $fetch.create.mockReturnValue(mockFetchFn) // 执行插件并获取注入的apiFetch方法 apiPlugin() const nuxtApp = useNuxtApp() const apiFetch = nuxtApp.provide.mock.calls[0][1] // 调用apiFetch并验证结果 const result = await apiFetch(mockEndpoint) expect(mockFetchFn).toHaveBeenCalledWith(mockEndpoint, expect.any(Object)) expect(result).toEqual(mockResponse) })
注意事项
- 确保Jest配置文件中正确处理Nuxt的路径别名(如
@/),可在jest.config.js中添加moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' } - 可扩展测试场景:比如模拟BASE_URL为空、请求失败等情况,覆盖更多边界条件
内容的提问来源于stack exchange,提问作者matt93
相关产品推荐
相关产品推荐

