Skip to content

Testing import.meta.client and/or import.meta.server #884

Answered by dulnan
dulnan asked this question in Q&A
Discussion options

You must be logged in to vote

In the meantime I found a solution that works for me. Instead of using import.meta.server or import.meta.client directly, I instead assign them to consts in a file, e.g. ~/helpers/importMeta.ts:

export const importMetaServer = import.meta.server

And then use it in the code I want to test:

import { importMetaServer } from '~/helpers/importMeta'

export function useFoobar() {
  if (importMetaServer) {
    return 'server'
  }
  return 'client'
}

Then it's possible to mock importMetaServer in tests:

import { useFoobar } from '~/composables/useFoobar'

const metaMock = vi.hoisted(() => ({
  importMetaServer: true,
}))

vi.mock('~/helpers/importMeta', () => metaMock)

function client() {
  meta…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@LLCampos
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by dulnan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants