Replies: 1 comment 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 one of my modules I have changed occurrences of
process.server
andprocess.client
toimport.meta.server
andimport.meta.client
. Previously I was able to write unit tests for both cases (e.g. when a component behaves differently on the client than on the server) by settingprocess.server = true
in my test case. However, usingimport.meta
, this does not work anymore. E.g.import.meta.server = true
, which kind of makes sense.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.
All reactions