-
In one of my modules I have changed occurrences of I have searched discussions and issues and wasn't able to find anyone having the same issue, so I'm starting to wonder if maybe I'm approaching this the wrong way anyway? If not, the question would be how I could unit test a component (or any code, really) for different client and server behaviour. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
To unit test a component that behaves differently on the client and server using Here is an example of how you can achieve this: // Import the functions to be tested
import { useServerOnlyComposable, useClientOnlyComposable } from './path/to/your/module';
// Mock import.meta properties
Object.defineProperty(import.meta, 'client', {
value: false,
writable: true,
});
Object.defineProperty(import.meta, 'server', {
value: true,
writable: true,
});
describe('useServerOnlyComposable', () => {
it('should throw an error when called on the client', () => {
import.meta.client = true;
expect(() => useServerOnlyComposable()).toThrow('this should not be called in the browser');
});
it('should not throw an error when called on the server', () => {
import.meta.client = false;
expect(() => useServerOnlyComposable()).not.toThrow();
});
});
describe('useClientOnlyComposable', () => {
it('should throw an error when called on the server', () => {
import.meta.server = true;
expect(() => useClientOnlyComposable()).toThrow('this should not be called on the server');
});
it('should not throw an error when called on the client', () => {
import.meta.server = false;
expect(() => useClientOnlyComposable()).not.toThrow();
});
}); In this example, we use Additionally, Nuxt provides a |
Beta Was this translation helpful? Give feedback.
-
In the meantime I found a solution that works for me. Instead of using 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 import { useFoobar } from '~/composables/useFoobar'
const metaMock = vi.hoisted(() => ({
importMetaServer: true,
}))
vi.mock('~/helpers/importMeta', () => metaMock)
function client() {
metaMock.importMetaServer = false
}
function server() {
metaMock.importMetaServer = true
}
describe('The composable', () => {
beforeEach(() => {
server()
})
it('works on server', () => {
expect(useFoobar()).toEqual('server')
})
it('works on client differently', () => {
client()
expect(useFoobar()).toEqual('client')
})
}) |
Beta Was this translation helpful? Give feedback.
In the meantime I found a solution that works for me. Instead of using
import.meta.server
orimport.meta.client
directly, I instead assign them to consts in a file, e.g.~/helpers/importMeta.ts
:And then use it in the code I want to test:
Then it's possible to mock
importMetaServer
in tests: