N
Nuxt2w ago
dmarr

Mocking auto-imported server utils in tests

I have a server util that uses a nuxt auto import. So there is no import { dbQuery } from './db' in my util that I want to test. In my .test file, I thought I could do:
vi.mock('../../../server/utils/db', () => {
return {
dbQuery: async () => [
vi.mock('../../../server/utils/db', () => {
return {
dbQuery: async () => [
but the test run fails because dbQuery is not found. I've tried using db ,dbQuery ,#imports in the mock path, but none work.
ReferenceError: dbQuery is not defined
ReferenceError: dbQuery is not defined
8 Replies
kapa.ai
kapa.ai2w ago
Hi @dmarr. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To mock auto-imported server utils in your Nuxt tests, you should use the mockNuxtImport function from @nuxt/test-utils/runtime instead of directly using vi.mock(). This is because Nuxt's auto-imports work differently than regular imports. Here's how you can mock your dbQuery utility:
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

// Mock the dbQuery function
mockNuxtImport('dbQuery', () => {
return async () => {
// Your mock implementation here
return ['mocked data']
}
})

// Your tests here
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

// Mock the dbQuery function
mockNuxtImport('dbQuery', () => {
return async () => {
// Your mock implementation here
return ['mocked data']
}
})

// Your tests here
If you need to change the implementation between tests, you can use vi.hoisted with mockNuxtImport:
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

const { dbQueryMock } = vi.hoisted(() => {
return {
dbQueryMock: vi.fn(async () => ['default mocked data'])
}
})

mockNuxtImport('dbQuery', () => {
return dbQueryMock
})

// Then in your test you can change the implementation
describe('my test', () => {
it('should work with different mock data', () => {
dbQueryMock.mockImplementation(async () => ['different mocked data'])
// Test with the new mock implementation
})
})
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

const { dbQueryMock } = vi.hoisted(() => {
return {
dbQueryMock: vi.fn(async () => ['default mocked data'])
}
})

mockNuxtImport('dbQuery', () => {
return dbQueryMock
})

// Then in your test you can change the implementation
describe('my test', () => {
it('should work with different mock data', () => {
dbQueryMock.mockImplementation(async () => ['different mocked data'])
// Test with the new mock implementation
})
})
Note that mockNuxtImport can only be used once per mocked import per test file because it gets transformed to vi.mock() which is hoisted in Vitest as documented in the Nuxt testing guide. For server utilities specifically, remember that Nuxt auto-imports from server/utils/ in the server directory, so you need to make sure you're mocking the correct function name as it's exported from your utility file. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@139883350096740354> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
dmarr
dmarrOP2w ago
I believe since it's a server based autoimport, this will not work. The error I get is: Error: Cannot find import "dbQuery" to mock @kapa.ai Error: Cannot find import "dbQuery" to mock
kapa.ai
kapa.ai2w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- If you're seeing the error "Cannot find import 'dbQuery' to mock", this typically means that the mockNuxtImport function couldn't locate the auto-import you're trying to mock. There are a few potential reasons for this: 1. The function name might not match exactly what's being auto-imported 2. The auto-import might be coming from a different location than expected 3. There might be an issue with how Nuxt is resolving the imports in the test environment Here are some approaches to fix this: Check the exact export name Make sure the function is exported with the exact name you're trying to mock. If your server utility file has:
// server/utils/db.js
export const dbQuery = async () => { /* ... */ }
// server/utils/db.js
export const dbQuery = async () => { /* ... */ }
Then the auto-import name should be dbQuery. Use the full path in mockNuxtImport Try specifying the full path to the utility:
mockNuxtImport('server:utils/db:dbQuery', () => {
return async () => ['mocked data']
})
mockNuxtImport('server:utils/db:dbQuery', () => {
return async () => ['mocked data']
})
Check if you need to mock #imports For some auto-imports, especially in newer Nuxt versions, you might need to mock the #imports virtual module:
vi.mock('#imports', () => {
return {
dbQuery: vi.fn().mockResolvedValue(['mocked data'])
}
})
vi.mock('#imports', () => {
return {
dbQuery: vi.fn().mockResolvedValue(['mocked data'])
}
})
Use vi.hoisted with mockNuxtImport As mentioned in the Nuxt testing documentation, you can try using vi.hoisted to ensure proper hoisting:
const { dbQuery } = vi.hoisted(() => {
return {
dbQuery: vi.fn().mockResolvedValue(['mocked data'])
}
})

mockNuxtImport('dbQuery', () => dbQuery)
const { dbQuery } = vi.hoisted(() => {
return {
dbQuery: vi.fn().mockResolvedValue(['mocked data'])
}
})

mockNuxtImport('dbQuery', () => dbQuery)
Check your Nuxt version In Nuxt 3.14+ with future.compatibilityVersion: 4 set, the auto-import behavior might be different, especially if you're using the new shared/ directory feature. Make sure your mocking approach matches your Nuxt version. If none of these approaches work, you might need to temporarily add an explicit import in your code to make it more testable, or consider restructuring your test to use a higher-level approach like mocking API responses instead of individual utility functions. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@139883350096740354> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
dmarr
dmarrOP2w ago
@kapa.ai no luck 😦 I feel like this is a quick answer, but I always get hung up finding support
kapa.ai
kapa.ai2w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I understand your frustration with mocking auto-imported server utilities. This can indeed be tricky in Nuxt. Let me suggest a different approach that has worked for others in similar situations:
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

// Use vi.hoisted to create the mock before any imports
const { useSupabaseClient } = vi.hoisted(() => {
return {
dbQuery: vi.fn().mockResolvedValue(['mocked data'])
}
})

// Then use mockNuxtImport with the exact function name
mockNuxtImport('dbQuery', () => useSupabaseClient.dbQuery)
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

// Use vi.hoisted to create the mock before any imports
const { useSupabaseClient } = vi.hoisted(() => {
return {
dbQuery: vi.fn().mockResolvedValue(['mocked data'])
}
})

// Then use mockNuxtImport with the exact function name
mockNuxtImport('dbQuery', () => useSupabaseClient.dbQuery)
This pattern was successful in a similar case for mocking Supabase in Nuxt tests as shown in this Stack Overflow answer. Alternatively, you could try looking at the generated types in .nuxt/types/imports.d.ts to see exactly how Nuxt has resolved your server utility auto-imports. This can give you insight into the correct import path to mock. If you're still having trouble, you might need to consider: 1. Temporarily adding explicit imports in your code for testing purposes 2. Using a higher-level testing approach (like testing the API endpoint instead of the utility directly) 3. Creating a small reproduction of your issue to share with the Nuxt community for more specific help The Nuxt team is quite responsive in GitHub Discussions if you need more specialized assistance with your specific setup. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@139883350096740354> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?