最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - vitest crypto.randomUUID() is not a function - Stack Overflow

programmeradmin4浏览0评论

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 ponent 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!

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 ponent 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!

Share Improve this question asked Sep 23, 2022 at 17:55 LunLun 1,1311 gold badge12 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

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.

Just checking, did you:

import crypto from 'node:crypto';

at some point?

发布评论

评论列表(0)

  1. 暂无评论