Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vitest crypto.randomUUID() is not a function

vite.config.ts

import { sveltekit } from '@sveltejs/kit/vite';

const config = {
    plugins: [sveltekit()],
    test: {
        include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
        environment: 'jsdom',
        globals: true,
        setupFiles: 'src/setupTests.ts'
    }
};

export default config;

src/setupTests.ts

import '@testing-library/jest-dom/extend-expect';

MyComponent.svelte

onMount(() => {
    postElementId = crypto.randomUUID();
    ...
});

Error

TypeError: crypto.randomUUID is not a function

I've got a component that uses the crypto api to create a random id and works as intended, but when I want to test it, everytime I do this error pops up, any help is appreciated!

like image 320
Lun Avatar asked Mar 13 '26 20:03

Lun


1 Answers

My vitest error was window.crypto.randomUUID() is not a function.

So, I added setupFiles to vite.config.js

test: {
    setupFiles: [
        './test/_setup/globalSetup.js'
    ],
...

Then, in globalSetup.js file I added these 2 lines:

import {randomUUID} from 'node:crypto';
window.crypto.randomUUID = randomUUID;

And it seems to have done the trick.

like image 182
Predrag Stojadinović Avatar answered Mar 15 '26 08:03

Predrag Stojadinović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!