7

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!

Lun
  • 861
  • 1
  • 10
  • 18

2 Answers2

3

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.

Predrag Stojadinović
  • 3,439
  • 6
  • 34
  • 52
  • Currently (May 5, 2023), the 'jsdom' environment is missing some crypto functionality, resulting in this error. There is an [open issue](https://github.com/jsdom/jsdom/issues/1612) for this on the [jsdom Github repo](https://github.com/jsdom/jsdom), including [a welcome](https://github.com/jsdom/jsdom/issues/1612#issuecomment-249441408) from one of the maintainers for folks to submit a PR. There are also several workarounds listed there that may work. Specifically for vitest, Predrag's answer here is an awesome workaround in the interim - please upvote. – Timothy Johns May 05 '23 at 16:30
1

Just checking, did you:

import crypto from 'node:crypto';

at some point?

Dylan Lacey
  • 1,839
  • 12
  • 23