lisonge / vite-plugin-monkey

A vite plugin server and build your.user.js for userscript engine like Tampermonkey, Violentmonkey, Greasemonkey, ScriptCat
MIT License
1.31k stars 70 forks source link

Problems with unit testing when the file imports another ts file that references $ to import GM_API #89

Closed cbarrerah closed 1 year ago

cbarrerah commented 1 year ago

Hi there,

Trying to unit test some methods inside the project that builds a tampermonkey script with react (react-ts config option) I have teh default settings react(), monkey({ clientAlias: "$", server: { mountGmApi: true, }, And it correctly builds and executes, but when trying to unit test with jester, it complains about the $ not being found: ` ● Test suite failed to run

Cannot find module '$' from 'src/common/Storage.tsx'

Require stack:
  src/common/Storage.tsx
  src/common/utils.tsx
  src/connectors/jira/actions/basic/Connection.tsx
  src/connectors/jira/actions/behavior/IssueLinker.tsx
  src/connectors/jira/actions/basic/DataFromResponse.tsx
  src/connectors/jira/actions/basic/LabelManagement.tsx
  test/connectors/jira/JiraResponseParsers.spec.ts

  1 | import { AUTH_TOKEN_NAMES, SCRIPT_IDENTIFIER } from "./ConfigConstants";
> 2 | import { GM_getValue, GM_setValue } from "$";
    | ^

`

Any idea if it is something missing from my config or from jest config to make it possible? Any guidance on how to unit test the react-ts project in a better way? Thanks. PS: BTW your project is amazing, it makes tampermonkey scripting a dream and enables creating complex scripts in a structured and sensible way, so thanks!! ^.^

lisonge commented 1 year ago

when vite serve, $ is vite-plugin-monkey/dist/client https://github.com/lisonge/vite-plugin-monkey/blob/133f6cc393c3785b28a0391c927ea0bae971ea0a/packages/vite-plugin-monkey/src/client/index.ts#L1-L174

when vite build, $ is vite-plugin-monkey/src/native, and vite-plugin-monkey/dist/client is still work but vite-plugin-monkey/src/native is better https://github.com/lisonge/vite-plugin-monkey/blob/133f6cc393c3785b28a0391c927ea0bae971ea0a/packages/vite-plugin-monkey/src/native/index.ts#L1-L31


Any idea if it is something missing from my config or from jest config to make it possible? Any guidance on how to unit test the react-ts project in a better way?

maybe it works

import type { Config } from 'jest';
import module from 'node:module';

export default <Config>{
  moduleNameMapper: {
    '^\\$$': module
      .createRequire(import.meta.url)
      .resolve('vite-plugin-monkey/dist/client'),
  },
};
cbarrerah commented 1 year ago

Sorry for the late response, I ended up fixing it by using vitest instead of jester, much simpler setup and it does handle the globals with a bit more grace than jester. Thanks anyway :)