Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't use global changes w/ a module (webcrypto-jwt) #528

Closed
6 tasks done
fadi-george opened this issue Jan 14, 2022 · 8 comments
Closed
6 tasks done

Can't use global changes w/ a module (webcrypto-jwt) #528

fadi-george opened this issue Jan 14, 2022 · 8 comments

Comments

@fadi-george
Copy link

fadi-george commented Jan 14, 2022

Describe the bug

jsonwebtoken is not something that can be used with Vite and so I have to use an alternative package like webcrypto-jwt for signing jwts. For testing, I get the error Error: crypto.subtle not found. So w/ Jest, I had to set that property in my setup test file, e.g.

Object.defineProperty(global, 'crypto', {
  value: {
    subtle: {
      importKey: () => Promise.resolve(''),
      sign: () => Promise.resolve(''),
    },
  },
  writable: true,
});

But with vitest, this doesn't work.

Reproduction

I have an example here:
https://stackblitz.com/edit/node-htxtbj?file=test%2FsomeActions.spec.tsx

But for whatever reason, this works in Stackblitz but downloading and running the project locally, it errors.

System Info

System:
    OS: macOS 12.1
    CPU: (8) arm64 Apple M1 Pro
    Memory: 89.92 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.13.1 - ~/.nvm/versions/node/v16.13.1/bin/node
    Yarn: 1.22.17 - ~/.nvm/versions/node/v16.13.1/bin/yarn
    npm: 8.1.2 - ~/.nvm/versions/node/v16.13.1/bin/npm
  Browsers:
    Brave Browser: 97.1.34.80
    Chrome: 97.0.4692.71
    Safari: 15.2
  npmPackages:
    @vitejs/plugin-react: ^1.1.4 => 1.1.4 
    vite: 2.7.11 => 2.7.11

Used Package Manager

npm

Validations

@sheremet-va
Copy link
Member

You need to have it on both global and window, since in Vitest it's different objects. Try:

const crypto = {
  subtle: {
    importKey: () => Promise.resolve(''),
    sign: () => Promise.resolve(''),
  },
}

Object.defineProperty(window, 'crypto', {
  value: crypto,
  writable: true,
});


Object.defineProperty(global, 'crypto', {
  value: crypto,
  writable: true,
});

@fadi-george
Copy link
Author

fadi-george commented Jan 14, 2022

@sheremet-va thanks, that works! Maybe we should have a similar behavior to jest (just a consideration).

@sheremet-va
Copy link
Member

sheremet-va commented Apr 5, 2022

@sheremet-va thanks, that works! Maybe we should have a similar behavior to jest (just a consideration).

We cannot run code similar to jest right now because of the poor ESM support (I am talking about vm module). So, right now the best way is to use vi.stubGlobal helper.

chaii3 pushed a commit to chaii3/vitest that referenced this issue May 13, 2022
* feat(useStorage): allow custom serializer

* update test
chaii3 pushed a commit to chaii3/vitest that referenced this issue May 13, 2022
* feat(useStorage): allow custom serializer

* update test
chaii3 pushed a commit to chaii3/vitest that referenced this issue May 13, 2022
* feat(useTransition): support for vectors (vitest-dev#376)

* refactor(useTransition): cleaning up (vitest-dev#385)

* refactor(useWebWorkerFn): Small doc and type improvements (vitest-dev#382)

Co-authored-by: Anthony Fu <[email protected]>

* feat: pwa reload prompt

* chore: update docs

* refactor(useWebWorkerFn): Small doc and type improvements (vitest-dev#382)

Co-authored-by: Anthony Fu <[email protected]>

* chore: update docs

* test: simpilfy tests for useTransition

* chore: fix tests

* feat(useTransition): support for delayed transitions (vitest-dev#386)

* feat(useTransition): support for disabled transitions (vitest-dev#436)

* feat!: introduce `controls` option

* chore: update

* chore: update

* refactor(useRafFn): remove depreacted APIs

* chore: enabled tests for next branch

* fix(useFetch)!: allow setting response type before doing request (vitest-dev#454)

Co-authored-by: Anthony Fu <[email protected]>

* chore: resolve conflicts

* feat(useMediaControls): expose source types (vitest-dev#495)

* fix(useMediaControls): Removes tracks that have been inserted in html (vitest-dev#493)

* chore: release v4.9.3

* fix(usePermission): tolerate error on FireFox

* fix(useDevicesList): treat as premssion granted after getUserMedia

* chore: release v4.9.4

* chore: fix typo (vitest-dev#502)

* feat(useWebSocket): add immediate option (vitest-dev#503)

* feat(useAxios): bring API into line with useFetch (vitest-dev#499)

* feat(createEventHook): new function (#497)

* chore: release v4.10.0

* fix(useMediaControls): Doesn't rewrite default media properties (vitest-dev#500)

* feat(useMediaControls): add error event (vitest-dev#509)

* feat(useStorage): optimize event handling logic (vitest-dev#505)

* feat(useFetch): add afterFetch option, onFetchResponse, and onFetchError (vitest-dev#506)

* feat(useWebWoker): return worker (vitest-dev#507)

Co-authored-by: Anthony Fu <[email protected]>

* fix: Change `onMediaError` to `onSourceError` (vitest-dev#510)

* feat(onClickOutside): default to just pointerDown (vitest-dev#508)

Co-authored-by: Anthony Fu <[email protected]>
Co-authored-by: sibbng <[email protected]>

* chore: update docs

* chore: release v4.11.0

* fix(onClickOutside): duplicate code (vitest-dev#519)

Co-authored-by: Nurettin Kaya <[email protected]>

* feat(createEventHook): added interface (vitest-dev#531)

* feat(createEventHook): added interface

* added types for EventHookOn, EventHookOff, and EventHook trigger

* feat(useStorage): allow custom serializer (vitest-dev#528)

* feat(useStorage): allow custom serializer

* update test

* refactor(useMediaControls): Deprecate options that can simply be set as attributes (vitest-dev#514)

* useMediaControls: Add `volumechange` event listener

* fix: `mute` returned

* feat: Deprecate video options:
* `poster`
* `autoplay`
* `preload`
* `loop`
* `controls`
* `playsinline`
* `autoPictureInPicture`

* fix: Fix deprecated behaviour in demo

* fix: Remove deprecated usage from doc

* refactor: More polite messages

* fix: Remove `console.warn`s

* chore: release v4.11.1

* refactor!: remove deprecated apis

* chore: add next tag

* chore: release v5.0.0-beta.1

* feat: introduce `components` & `directives` (vitest-dev#486)

Co-authored-by: Anthony Fu <[email protected]>

* docs: re-organize

* chore: fix lint

* docs: about components

* chore: include directives

* chore: release v5.0.0-beta.2

* chore: rollback jest

* chore: fix docs build

* docs: readme for components

* docs: add @vueuse/gesture

* chore: ship indexes.json

* chore: release v5.0.0-beta.3

* feat(typedef): add return typedefs (vitest-dev#543) (vitest-dev#544)

* refactor!: change publish strcture and support submodules, close vitest-dev#469

* chore: cleanup stories.tsx

* docs: update docs about submodules

* chore: fix docs

* chore: release v5.0.0-beta.4

* chore: update lock

* chore: release v5.0.0-beta.5

* chore: update deps and extend publish memory

* refactor: remove `useDeviceLight`

* chore: update

* chore: fix tests

* chore: release v5.0.0-beta.7

* refactor(useWebSocket)!: change immediate default for 5.0.0 (vitest-dev#545)

* feat(useIpcRenderer): new add-one & new functions (vitest-dev#547)

Co-authored-by: Anthony Fu <[email protected]>

* chore: update deps

* chore: release v5.0.0-beta.8

* chore: fix docs build

* chore(usePointerSwipe): fix typo (vitest-dev#557)

* fix(useAuth): now reqiures the auth instance, close vitest-dev#538

* chore: update deps

* docs(biSyncRef): fix console output comment (vitest-dev#555)

* docs: removed deprecated value from example (vitest-dev#556)

* docs(guidlines): added guidelines (vitest-dev#535)

* docs: update guidelines

* chore: update guidelines

Co-authored-by: Scott Bedard <[email protected]>
Co-authored-by: Fabian <[email protected]>
Co-authored-by: Ismail Gjevori <[email protected]>
Co-authored-by: Alex Kozack <[email protected]>
Co-authored-by: Shinigami <[email protected]>
Co-authored-by: wheat <[email protected]>
Co-authored-by: sibbng <[email protected]>
Co-authored-by: JserWang <[email protected]>
Co-authored-by: Pig Fang <[email protected]>
Co-authored-by: ArcherGu <[email protected]>
Co-authored-by: Ilya Komichev <[email protected]>
Co-authored-by: Daiki Ojima <[email protected]>
Co-authored-by: Manaus <[email protected]>
@macmillen
Copy link

@sheremet-va Somehow when using vi.stubGlobal it only works when I'm adding the mock directly into the source code file and not just the test file.

const cryptoMock = { randomUUID: vi.fn(() => Math.random()) };
vi.stubGlobal("crypto", cryptoMock);

@sheremet-va
Copy link
Member

@sheremet-va Somehow when using vi.stubGlobal it only works when I'm adding the mock directly into the source code file and not just the test file.

Maybe you are trying to stub after you import a module that uses it? That way module will already be evaluated with original crypto.

@macmillen
Copy link

@sheremet-va Somehow when using vi.stubGlobal it only works when I'm adding the mock directly into the source code file and not just the test file.

Maybe you are trying to stub after you import a module that uses it? That way module will already be evaluated with original crypto.

You are right, thank you! 🙏

But now my imports look like this:

import { vi } from "vitest";
const cryptoMock = { randomUUID: vi.fn(() => Math.random()) };
vi.stubGlobal("crypto", cryptoMock);

import { createBlockStore } from "./block.store";

I guess there is no prettier way of doing this until jsdom supports randomUUID.

@sheremet-va
Copy link
Member

But now my imports look like this:

You can use setupFiles in your config to stub crypto, they are called before tests.

@macmillen
Copy link

You can use setupFiles in your config to stub crypto, they are called before tests.

Awesome, thank you! 👌

@vitest-dev vitest-dev locked as resolved and limited conversation to collaborators Jul 31, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants