Coder Social home page Coder Social logo

vite-jest's Introduction

vite-jest

First-class Vite integration for Jest.

Still work-in-progress, here are some working examples:

Usage:

  1. Add preset: 'vite-jest' to your Jest config.
  2. Replace the jest CLI with vite-jest.

See ./packages/vite-jest/README.md for more detailed guidelines and implementation notes.

vite-jest's People

Contributors

benmccann avatar carlalbrecht avatar diegoleme avatar maxbeatty avatar rek avatar sodatea avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-jest's Issues

Unexpected token '??='

Test suite failed to run

    SyntaxError: Unexpected token '??='

Can this syntax be enabled?

still maintained?

Hi is this repo still maintained? I can't get vite-jest to install with vite >=4 I have recently migrated quite a large vue2 project to vue3 and vite but now trying to get my jest tests to work again as I can't rewrite all my components in one big bang to use vitest, my PO will murder me.

react-app-ts example is broken

Repro repository here: https://github.com/SQReder/vite-jest-coverage-issue

> @0.0.0 test:unit /home/username/_proj/vite-jest-coverage
> vite-jest

(node:717715) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Pre-bundling dependencies:
  react
  react-dom
(this will be run only when your dependencies or config have changed)
 FAIL  src/App.test.tsx
  ✕ renders learn react link (73 ms)

  ● renders learn react link

    Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

       5 |
       6 | const App: React.FC<{ initial?: number }> = ({ initial = 0 }) => {
    >  7 |   const [count, setCount] = useState(initial);
         |                             ^
       8 |
       9 |   return (
      10 |     <div className={styles.app}>

      at resolveDispatcher (node_modules/react/cjs/react.development.js:1476:13)
      at App (src/App.tsx:7:29)
      at Object.<anonymous> (src/App.test.tsx:7:3)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.092 s
Ran all test suites.
  console.error
    Error: Uncaught [Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.]
        at reportException (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)
        at innerInvokeEventListeners (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:341:9)
        at invokeEventListeners (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
        at HTMLUnknownElementImpl._dispatch (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
        at HTMLUnknownElementImpl.dispatchEvent (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
        at HTMLUnknownElement.dispatchEvent (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
        at Object.invokeGuardedCallbackDev (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:3994:16)
        at invokeGuardedCallback (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:4056:31)
        at beginWork$1 (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:23964:7)
        at performUnitOfWork (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:22779:12) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
        at resolveDispatcher (/home/username/_proj/vite-jest-coverage/node_modules/react/cjs/react.development.js:1476:13)
        at useState (/home/username/_proj/vite-jest-coverage/node_modules/react/cjs/react.development.js:1507:20)
        at App (/home/username/_proj/vite-jest-coverage/src/App.tsx:7:29)
        at renderWithHooks (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:14985:18)
        at mountIndeterminateComponent (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:17811:13)
        at beginWork (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:19049:16)
        at HTMLUnknownElement.callCallback (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:3945:14)
        at HTMLUnknownElement.callTheUserObjectsOperation (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
        at innerInvokeEventListeners (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:338:25)
        at invokeEventListeners (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
        at HTMLUnknownElementImpl._dispatch (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
        at HTMLUnknownElementImpl.dispatchEvent (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
        at HTMLUnknownElement.dispatchEvent (/home/username/_proj/vite-jest-coverage/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
        at Object.invokeGuardedCallbackDev (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:3994:16)
        at invokeGuardedCallback (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:4056:31)
        at beginWork$1 (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:23964:7)
        at performUnitOfWork (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:22779:12)
        at workLoopSync (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:22707:5)
        at renderRootSync (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:22670:7)
        at performSyncWorkOnRoot (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:22293:18)
        at scheduleUpdateOnFiber (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:21881:7)
        at updateContainer (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:25482:3)
        at /home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:26021:7
        at unbatchedUpdates (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:22431:12)
        at legacyRenderSubtreeIntoContainer (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:26020:5)
        at Object.render (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:26103:10)
        at /home/username/_proj/vite-jest-coverage/node_modules/@testing-library/react/dist/pure.js:101:25
        at batchedUpdates$1 (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom.development.js:22380:12)
        at act (/home/username/_proj/vite-jest-coverage/node_modules/react-dom/cjs/react-dom-test-utils.development.js:1042:14)
        at render (/home/username/_proj/vite-jest-coverage/node_modules/@testing-library/react/dist/pure.js:97:26)
        at Object.<anonymous> (/home/username/_proj/vite-jest-coverage/src/App.test.tsx:7:3)
        at Promise.then.completed (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/utils.js:390:28)
        at new Promise (<anonymous>)
        at callAsyncCircusFn (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/utils.js:315:10)
        at _callCircusTest (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/run.js:218:40)
        at processTicksAndRejections (internal/process/task_queues.js:95:5)
        at _runTest (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/run.js:155:3)
        at _runTestsForDescribeBlock (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/run.js:66:9)
        at run (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/run.js:25:3)
        at runAndTransformResultsToJestFormat (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:167:21)
        at jestAdapter (/home/username/_proj/vite-jest-coverage/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js:82:19)
        at runTestInternal (/home/username/_proj/vite-jest-coverage/node_modules/jest-runner/build/runTest.js:389:16)
        at runTest (/home/username/_proj/vite-jest-coverage/node_modules/jest-runner/build/runTest.js:475:34)
        at TestRunner.runTests (/home/username/_proj/vite-jest-coverage/node_modules/jest-runner/build/index.js:111:12)
        at TestScheduler.scheduleTests (/home/username/_proj/vite-jest-coverage/node_modules/@jest/core/build/TestScheduler.js:333:13)
        at runJest (/home/username/_proj/vite-jest-coverage/node_modules/@jest/core/build/runJest.js:387:19)
        at _run10000 (/home/username/_proj/vite-jest-coverage/node_modules/@jest/core/build/cli/index.js:408:7)
        at runCLI (/home/username/_proj/vite-jest-coverage/node_modules/@jest/core/build/cli/index.js:261:3)
        at Object.run (/home/username/_proj/vite-jest-coverage/node_modules/jest-cli/build/cli/index.js:163:37)

      at VirtualConsole.<anonymous> (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)

  console.error
    The above error occurred in the <App> component:
    
        at App (/home/username/_proj/vite-jest-coverage/src/App.tsx:6:48)
    
    Consider adding an error boundary to your tree to customize error handling behavior.
    Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

      at logCapturedError (node_modules/react-dom/cjs/react-dom.development.js:20085:23)

/home/username/_proj/vite-jest-coverage/node_modules/execa/lib/error.js:60
                error = new Error(message);
                        ^

Error: Command failed with exit code 1: node --experimental-vm-modules /home/username/_proj/vite-jest-coverage/node_modules/jest/bin/jest.js
    at makeError (/home/username/_proj/vite-jest-coverage/node_modules/execa/lib/error.js:60:11)
    at Function.module.exports.sync (/home/username/_proj/vite-jest-coverage/node_modules/execa/index.js:194:17)
    at file:///home/username/_proj/vite-jest-coverage/node_modules/vite-jest/bin/vite-jest.js:11:7
    at ModuleJob.run (internal/modules/esm/module_job.js:170:25)
    at async Loader.import (internal/modules/esm/loader.js:178:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5) {
  shortMessage: 'Command failed with exit code 1: node --experimental-vm-modules /home/username/_proj/vite-jest-coverage/node_modules/jest/bin/jest.js',
  command: 'node --experimental-vm-modules /home/username/_proj/vite-jest-coverage/node_modules/jest/bin/jest.js',
  escapedCommand: 'node --experimental-vm-modules "/home/username/_proj/vite-jest-coverage/node_modules/jest/bin/jest.js"',
  exitCode: 1,
  signal: undefined,
  signalDescription: undefined,
  stdout: undefined,
  stderr: undefined,
  failed: true,
  timedOut: false,
  isCanceled: false,
  killed: false
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @0.0.0 test:unit: `vite-jest`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @0.0.0 test:unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/username/.npm/_logs/2021-09-29T13_40_42_893Z-debug.log

Process finished with exit code 1

vite-jest: 0.0.3
node: v14.17.5

TypeError: (0 , _loadBabelConfig.loadPartialConfigAsync) is not a function when loading test suites

When I run my tests, every suite fails with the "is not a function" error in the issue title. Here are the full details for one failure:

 FAIL  app/javascript/util/map.test.ts
  ● Test suite failed to run

    TypeError: (0 , _loadBabelConfig.loadPartialConfigAsync) is not a function

      at loadBabelConfigAsync (node_modules/babel-jest/build/index.js:197:73)
      at ScriptTransformer._getCacheKeyAsync (node_modules/@jest/transform/build/ScriptTransformer.js:313:37)
      at ScriptTransformer._getFileCachePathAsync (node_modules/@jest/transform/build/ScriptTransformer.js:357:33)
      at ScriptTransformer.transformSourceAsync (node_modules/@jest/transform/build/ScriptTransformer.js:637:38)
      at ScriptTransformer._transformAndBuildScriptAsync (node_modules/@jest/transform/build/ScriptTransformer.js:717:46)
      at ScriptTransformer.transformAsync (node_modules/@jest/transform/build/ScriptTransformer.js:789:25)

This is my jest config:

module.exports = {
  preset: 'vite-jest',
  testEnvironment: 'jsdom',
  globalSetup: './app/javascript/jestTestSetup',
  testMatch: [ "**/app/javascript/**/?(*.)+(spec|test).[jt]s?(x)" ],
  moduleDirectories: [ "node_modules", "app/javascript" ],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    "\\.(css)$": "identity-obj-proxy",
  },
  transform: {
    "^.+\\.[t|j]sx?$": "babel-jest",
    "\\.(graphql)$": "<rootDir>/__mocks__/graphqlMock.js",
  },
};

Versions:

jest: 27.2.4
babel-jest: 27.2.4
vite-jest: 0.0.3

Any ideas?

Watch mode with `vite-jest --watch`

I can only press a once to re-run the tests, then after second run I get

  ● Test suite failed to run

    Server is not running.

and can't re-run tests anymore.

Running test:unit in the react-app-ts and react-app-type-module examples folder fails on Windows

Hi there,

I've tried to use vite-jest on a small demo project and it failed with the same error I get when I try to run the examples test:unit script... It might be some Windows paths shenanigans but I am not sure...

Both projects (react-app-ts and react-app-type-module) successfully bundle (prod mode) and start in DEV mode.

If there is anything I can do to help, holla at me.

The error log:

> @0.0.0 test:unit E:\Projects\vite-jest\examples\react-app-ts
> vite-jest

● Validation Error:

  Module /E:/Projects/vite-jest/packages/vite-jest/index.js in the transform option was not found.
         <rootDir> is: E:\Projects\vite-jest\examples\react-app-ts

  Configuration Documentation:
  https://jestjs.io/docs/configuration

E:\Projects\vite-jest\node_modules\.pnpm\[email protected]\node_modules\execa\lib\error.js:60
                error = new Error(message);
                        ^

Error: Command failed with exit code 1: node --experimental-vm-modules E:\Projects\vite-jest\node_modules\.pnpm\[email protected]\node_modules\jest\bin\jest.js
    at makeError (E:\Projects\vite-jest\node_modules\.pnpm\[email protected]\node_modules\execa\lib\error.js:60:11)
    at Function.module.exports.sync (E:\Projects\vite-jest\node_modules\.pnpm\[email protected]\node_modules\execa\index.js:194:17)
    at file:///E:/Projects/vite-jest/packages/vite-jest/bin/vite-jest.js:11:7
    at ModuleJob.run (node:internal/modules/esm/module_job:175:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
    at async handleMainPromise (node:internal/modules/run_main:63:12) {
  shortMessage: 'Command failed with exit code 1: node --experimental-vm-modules E:\\Projects\\vite-jest\\node_modules\\.pnpm\\[email protected]\\node_modules\\jest\\bin\\jest.js',  command: 'node --experimental-vm-modules E:\\Projects\\vite-jest\\node_modules\\.pnpm\\[email protected]\\node_modules\\jest\\bin\\jest.js',
  escapedCommand: 'node --experimental-vm-modules "E:\\Projects\\vite-jest\\node_modules\\.pnpm\\[email protected]\\node_modules\\jest\\bin\\jest.js"',
  exitCode: 1,
  signal: undefined,
  signalDescription: undefined,
  stdout: undefined,
  stderr: undefined,
  failed: true,
  timedOut: false,
  isCanceled: false,
  killed: false
}

Sys info:

  System:
    OS: Windows 10 10.0.19043
    CPU: (16) x64 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
    Memory: 17.81 GB / 31.92 GB
  Binaries:
    Node: 16.4.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.10 - C:\Program Files\nodejs\yarn.CMD
    npm: 7.19.1 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 91.0.4472.124
    Edge: Spartan (44.19041.1023.0), Chromium (91.0.864.67)
    Internet Explorer: 11.0.19041.1

Issues with running tests that import ES modules

I am using vite-jest 0.0.3, running my tests with vite-jest. I am seeing failures across all my tests for essentially the same reason. Here is a screenshot of the first failure that looks like an esm syntax issue:

image

jest config looks like this:

const config = {
  preset: 'vite-jest',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testMatch: ['<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}', '<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}'],
  testEnvironment: 'jest-environment-jsdom',
}

vite config looks like this:

import {defineConfig} from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'

export default defineConfig({
  build: {
    outDir: 'build',
  },
  plugins: [...(process.env.NODE_ENV !== 'test' ? [reactRefresh()] : [])],
})

Multiple issues when running vite-jest: fsevents .node, jest-pnp-resolver defaultResolver, ReferenceError: __DEFINES__

I ran into multiple issues while trying to add (vite-)jest to a vite: vanilla-ts project.

As far as I can tell, these issues are actually caused upstream and therefore not actually issues with vite or vite-jest, they seem mostly limitations of esbuild and rollup.

Also, I could not find a solution that could be implemented in vite-jest, of course I could be wrong...

However, it did stop me from using vite and vite-jest 'out-of-the-box' and therefore want to throw it out here, so other people running into the issue(s) might not have to spend a few days on finding a solution or workaround.

Reproduction:

https://github.com/PeterDeKok/reproduce_sodatea_vite-jest_dependency_errors

TLDR Below.

yarn/1.22.17 npm/8.5.0 node/v16.14.2 darwin x64

A project created with vite vanilla-ts template, with added jest and vite-jest.

Running yarn test:unit, gives the following errors:

[vite] error while updating dependencies:
Error: Build failed with 4 errors:
node_modules/fsevents/fsevents.js:13:23: ERROR: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node
node_modules/jest-pnp-resolver/index.js:46:4: ERROR: Cannot assign to "defaultResolver" because it is a constant
node_modules/vite/dist/node/chunks/dep-9c153816.js:28849:7: ERROR: [plugin: vite:dep-pre-bundle] Missing "./build/defaultResolver" export in "jest-resolve" package
node_modules/vite/dist/node/chunks/dep-9c153816.js:28849:7: ERROR: [plugin: vite:dep-pre-bundle] Missing "./build/default_resolver" export in "jest-resolve" package
    at failureErrorWithLog (.../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:1599:15)
    at .../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:1245:28
    at runOnEndCallbacks (.../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:1030:63)
    at buildResponseToResult (.../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:1243:7)
    at .../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:1352:14
    at .../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:662:9
    at handleIncomingPacket (.../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:759:9)
    at Socket.readFromStdout (.../reproduce_sodatea_vite-jest_dependency_errors/node_modules/esbuild/lib/main.js:629:7)
    at Socket.emit (node:events:526:28)
    at addChunk (node:internal/streams/readable:315:12)

By excluding fsevents and jest-pnp-resolver, from dependency optimization, these errors are no longer thrown.

However, on top of 2 warnings about unsupported async import syntax, a new error pops up:

ReferenceError: __DEFINES__ is not defined

      at node_modules/vite/src/client/env.ts:17:17
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)

Possibly related issues:
evanw/esbuild#1715

TLDR;

By exluding (only) jest, from dependency optimization, all errors seem gone.

// vite.config.ts
import { defineConfig } from 'vite';

export default defineConfig({
	optimizeDeps: {
        exclude: [ 'jest' ],
    },
});

Cannot find module '../node_modules/.vite/@vue_test-utils.js' from 'src/App.spec.ts'

First of all, thanks a lot for your hard work on supporting jest on vite.

When I first setup the project with vite-jest, my tests were working again, felt like magic, however, I noticed jest wasn't exiting and instead giving me this message:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

Since this issue was getting the commits stuck due to a git hook that runs unit tests, I decided to investigate further in order to solve it.

I gave it a try with --detectOpenHandles but didn't got any additional output. I even tried passing --forceExit with no luck.

I excluded some tests and even wrote a simple one and still got the same issue.

After a lot of trial and error... I ended removing the node_modules directory and installed all packages all over again and now the unit tests are failing with the above-mentioned message.

This is my test file:

// App.spec.ts
import { mount, shallowMount } from "@vue/test-utils";
import App from "./App.vue";
import router from "./router";

test("uses mounts", () => {
  const wrapper = mount(App, {
    global: {
      plugins: [router]
    }
  });
  expect(wrapper.html()).toContain("Home");
  expect(wrapper.html()).not.toContain("Hello world");
});

test("uses shallowMount", () => {
  const wrapper = shallowMount(App, {
    global: {
      plugins: [router]
    }
  });
  expect(wrapper.html()).toContain("Home");
  expect(wrapper.html()).not.toContain("Hello world");
});

Any hints on what is causing it and how I can make it work again? And also fix the issue about jest not exiting.

Running examples/vue-app-ts tests throws "Preset vite-jest is invalid"

Runnig vite-jest in example vue-app-ts throws an error.

Steps to reproduce

  1. git clone [email protected]:sodatea/vite-jest.git

  2. cd examples/vue-app-ts

  3. Update package.json

    -    "vite-jest": "workspace:*",
    +    "vite-jest": "^0.0.3",
    
  4. npm i

  5. npm run test:unit

    $ npm run test:unit
    
    > test:unit
    > vite-jest
    
    ● Validation Error:
    
      Preset vite-jest is invalid:
    
      String.prototype.startsWith called on null or undefined
      TypeError: String.prototype.startsWith called on null or undefined
        at startsWith (<anonymous>)
        at node:internal/errors:811:19
        at Array.filter (<anonymous>)
        at node:internal/errors:809:16
        at prepareStackTrace (node:internal/errors:96:12)
        at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:38)
        at Module.load (node:internal/modules/cjs/loader:981:32)
        at Function.Module._load (node:internal/modules/cjs/loader:822:12)
        at Module.require (node:internal/modules/cjs/loader:1005:19)
        at require (node:internal/modules/cjs/helpers:94:18)
    
      Configuration Documentation:
      https://jestjs.io/docs/configuration
    
    /path/to/project/vite-jest/examples/vue-app-ts/node_modules/execa/lib/error.js:60
                    error = new Error(message);
                            ^
    
    Error: Command failed with exit code 1: node --experimental-vm-modules /path/to/project/vite-jest/examples/vue-app-ts/node_modules/jest/bin/jest.js
        at makeError (/path/to/project/vite-jest/examples/vue-app-ts/node_modules/execa/lib/error.js:60:11)
        at Function.module.exports.sync (/path/to/project/vite-jest/examples/vue-app-ts/node_modules/execa/index.js:194:17)
        at file:///path/to/project/vite-jest/examples/vue-app-ts/node_modules/vite-jest/bin/vite-jest.js:11:7
        at ModuleJob.run (node:internal/modules/esm/module_job:183:25)
        at async Loader.import (node:internal/modules/esm/loader:178:24)
        at async Object.loadESM (node:internal/process/esm_loader:68:5)
        at async handleMainPromise (node:internal/modules/run_main:63:12) {
      shortMessage: 'Command failed with exit code 1: node --experimental-vm-modules /path/to/project/vite-jest/examples/vue-app-ts/node_modules/jest/bin/jest.js',
      command: 'node --experimental-vm-modules /path/to/project/vite-jest/examples/vue-app-ts/node_modules/jest/bin/jest.js',
      escapedCommand: 'node --experimental-vm-modules "/path/to/project/vite-jest/examples/vue-app-ts/node_modules/jest/bin/jest.js"',
      exitCode: 1,
      signal: undefined,
      signalDescription: undefined,
      stdout: undefined,
      stderr: undefined,
      failed: true,
      timedOut: false,
      isCanceled: false,
      killed: false
    }

Environment info

MacOS Big Sur 11.5.1

$ npm --version
7.19.1
$ node --version
v16.6.0

Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.

When trying to run this in my project I get this error for all my 144 test suites:

  ● Test suite failed to run

    Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.

      at Object.get (node_modules/.vite/browser-external:stream:3:11)
      at node_modules/node-fetch/lib/index.mjs (node_modules/node-fetch/lib/index.mjs:11:25)
      at __init (node_modules/.vite/chunk-32SO2RNX.js:33:56)
      at node_modules/msw/lib/esm/fetch-deps.js:968:48
          at runMicrotasks (<anonymous>)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)

Any idea what this means?

Not working with typescript and jsx

First off, I'm glad work is being done in this space! Being able to use jest with vite will really solidify it as the next big framework in my mind.

This doesn't seem to be working with TypeScript and jsx, but only if the jsx is within the test file. jsx in the files being imported seems to be working fine. I'm migrating a create-react-app project over and I have the boilerplate test still, looking like this:

// App.test.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import { App } from '../App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

which fails with:

Click to expand
> vite-jest

(node:73359) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 PASS  src/utils/__tests__/isSet.test.ts
 FAIL  src/__tests__/App.test.tsx
  ● Test suite failed to run

    SyntaxError: Unexpected token '<'

      at Runtime.loadEsmModule (node_modules/jest-runtime/build/index.js:577:24)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:387:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)

Test Suites: 1 failed, 1 passed, 2 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        1.76 s
Ran all test suites.
/Volumes/Media/bschlenk/Workspace/set/node_modules/execa/lib/error.js:60
                error = new Error(message);
                        ^

Error: Command failed with exit code 1: node --experimental-vm-modules /Volumes/Media/bschlenk/Workspace/set/node_modules/jest/bin/jest.js 
    at makeError (/Volumes/Media/bschlenk/Workspace/set/node_modules/execa/lib/error.js:60:11)
    at Function.module.exports.sync (/Volumes/Media/bschlenk/Workspace/set/node_modules/execa/index.js:194:17)
    at file:///Volumes/Media/bschlenk/Workspace/set/node_modules/vite-jest/bin/vite-jest.js:14:7
    at ModuleJob.run (internal/modules/esm/module_job.js:169:25)
    at async Loader.import (internal/modules/esm/loader.js:177:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5) {
  shortMessage: 'Command failed with exit code 1: node --experimental-vm-modules /Volumes/Media/bschlenk/Workspace/set/node_modules/jest/bin/jest.js ',
  command: 'node --experimental-vm-modules /Volumes/Media/bschlenk/Workspace/set/node_modules/jest/bin/jest.js ',
  escapedCommand: 'node --experimental-vm-modules "/Volumes/Media/bschlenk/Workspace/set/node_modules/jest/bin/jest.js" ',
  exitCode: 1,
  signal: undefined,
  signalDescription: undefined,
  stdout: undefined,
  stderr: undefined,
  failed: true,
  timedOut: false,
  isCanceled: false,
  killed: false
}

But if I change the test to

// App.test.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import { App } from '../App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(React.createElement(App), div); // <-- replaced jsx with React.createElement
  ReactDOM.unmountComponentAtNode(div);
});

then it passes.

Jest is not defined in examples/react-app-ts

When i try to run examples/react-app-ts and reference the global jest in the tests an exception is thrown:

$ vite-jest
(node:54191) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  src/App.test.tsx
  ● Test suite failed to run

    ReferenceError: jest is not defined

      4 | import App from './App';
      5 |
    > 6 | const fn = jest.fn()
        |            ^
      7 |
      8 | test('renders learn react link', () => {
      9 |   render(<App />);

      at src/App.test.tsx:6:12
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:387:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.05 s
Ran all test suites.
<somePath>/vite-jest/examples/react-app-ts/node_modules/execa/lib/error.js:60
		error = new Error(message);
		        ^

Error: Command failed with exit code 1: node --experimental-vm-modules <somePath>/vite-jest/examples/react-app-ts/node_modules/jest/bin/jest.js
    at makeError (<somePath>vite-jest/examples/react-app-ts/node_modules/execa/lib/error.js:60:11)
    at Function.module.exports.sync (<somePath>/vite-jest/examples/react-app-ts/node_modules/execa/index.js:194:17)
    at file://<somePath>/vite-jest/examples/react-app-ts/node_modules/vite-jest/bin/vite-jest.js:11:7
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:177:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5) {
  shortMessage: 'Command failed with exit code 1: node --experimental-vm-modules<somePath>/vite-jest/examples/react-app-ts/node_modules/jest/bin/jest.js',
  command: 'node --experimental-vm-modules <somePath>/vite-jest/examples/react-app-ts/node_modules/jest/bin/jest.js',
  escapedCommand: 'node --experimental-vm-modules "<somePath>/vite-jest/examples/react-app-ts/node_modules/jest/bin/jest.js"',
  exitCode: 1,
  signal: undefined,
  signalDescription: undefined,
  stdout: undefined,
  stderr: undefined,
  failed: true,
  timedOut: false,
  isCanceled: false,
  killed: false
}
error Command failed with exit code 1.

vite-jest fails to import module chunks?

running vite-jest 0.0.3, seeing the following issue:
image

Same setup/configuration as in #11 — I am not sure if this issue is related, the error message looked different enough for me to break this out in to a separate ticket.

Edit: I wonder if this may have something to do with yarn workspaces, and that these dependencies are hoisted into the root node_modules.

Error when using vite-react-jsx

We are using the new jsx runtime using vite-react-jsx, but this causes an error when we run tests. I have reproduced it here: https://github.com/jonrimmer/vite-jest/tree/problem-jsx

The app runs fine when I run pnpnm dev, but when I run pnpm jest:unit on react-app-ts example, I get an error saying React is not defined...

 FAIL  src/App.test.tsx
  ✕ renders learn react link (52 ms)

  ● renders learn react link

    ReferenceError: React is not defined

       7 |   const [count, setCount] = useState(initial);
       8 |
    >  9 |   return (
         |   ^
      10 |     <div className={styles.app}>
      11 |       <header className={styles.appHeader}>
      12 |         <img src={logo} className={styles.appLogo} alt="logo" />

      at App (src/App.tsx:9:3)
      at Object.<anonymous> (src/App.test.tsx:5:3)

  console.error
    Error: Uncaught [ReferenceError: React is not defined]

...but the React import should be automatically added when I am using vite-react-jsx.

Coverage report generates fingerprints in filenames

If I turn collectCoverage on in my jest.config.js, the generated coverage report adds fingerprints into the names of the files (e.g. Button.tsx?1643925799148). This not only breaks the HTML report (as the filenames of the pages for the individual files include the question marks), but generates a new file per tested file for each test run!

I'm struggling to find a configuration option to turn this behaviour off, even just in the test environment.

react ts app `yarn test:unit` fails with `SyntaxError: Cannot use import statement outside a module`

Thank you for your work on this package and apologies in advance if this issue is the result of user error.

I see the following error in the example react-app-ts and also when incorporating vite-jest into my own react app.

/code/vite-jest/examples/react-app-ts/node_modules/vite-jest/bin/vite-jest.js:3
import fs from 'fs'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11

Jest did not exit one second after the test run has completed

Hi!

In my current setup I'm using the following versions

"scripts": {
	"test": "vite-jest",
},
"devDependencies": {
	"jest": "^27.4.3",
	"jest-environment-jsdom": "^27.4.3",
	"vite": "^2.7.1",
	"vite-jest": "^0.1.4"
}

My test runs fine and everything passes, but after that, I get the following message:

Ran all test suites.
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

And the process just hangs.
This is fine for local development (I can just CTRL+C), but it freezes my CI pipeline.

testing in `jest-environment-node`

Hi there,

I'm trying to test in jest-environment-node and getting some errors.

In your examples/vue-app-ts, I did

  • yarn add jest-environment-node -D
  • put jest-environment-node as testEnvironment in jest.config.js
  • update HelloWorld.spec.ts to the following:
import fs from "fs";

console.log("# fs", fs.readFileSync);

it("test nothing", () => {
  expect(true).toEqual(true);
});

Then I get this error when running the test:

  ● Test suite failed to run

    Module "fs" has been externalized for browser compatibility and cannot be accessed in client code.

      at Object.get (node_modules/.vite-jest-cache/__slash__@id__slash____vite-browser-external__colon__fs.js:3:11)
      at src/components/__tests__/HelloWorld.spec.ts?1639665446845:3:24
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)

Do I need to do something in the vite.config.ts?

  • MacOS: BigSur 11.6.1
  • NodeJS: 14.17.6

Cannot find module '../node_modules/.vite/@testing-library_react.js' from 'src/__tests__/unit/App.test.tsx'

I am running a very basic test copied from the React + Typescript example.

import React from "react";

import { render, screen } from "@testing-library/react";
import App from "../../App";

test("renders learn react link", () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

Sadly, it throws me an error

Test suite failed to run

    Cannot find module '.../node_modules/.vite/@testing-library_react.js' from 'src/__tests__/unit/App.test.tsx'

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:318:11)

I checked my .vite folder, I do have testing library react js installed

image

This is my package.json
image

I have tried placing it under dependencies and also devDependencies, but nothing seems to work.

Any ideas?

My full package.json. I really want to use vite-jest ! But if this doesn't work, I would have to go back to my hackish babel method of running jest with vite.

"scripts": {
    "dev": "vite --host",
    "build": "./build.sh",
    "serve": "vite preview",
    "lint": "eslint src",
    "test:unit": "vite-jest"
  },
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^12.0.0",
    "react": "^17.0.0",
    "react-dom": "^17.0.0"
  },
  "devDependencies": {
    "@types/jest": "^27.0.1",
    "@types/node": "^16.9.0",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@typescript-eslint/eslint-plugin": "^4.31.0",
    "@vitejs/plugin-react-refresh": "^1.3.1",
    "autoprefixer": "^10.3.4",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.25.1",
    "jest": "^27.1.1",
    "jest-environment-jsdom": "^27.1.1",
    "postcss": "^8.3.6",
    "tailwindcss": "^2.2.13",
    "typescript": "^4.3.2",
    "vite": "^2.5.4",
    "vite-jest": "^0.0.3"
  }

Random errors when running test with jest CLI

I wanted to use vite-jest as my test running with @testing-library/user-event and the test runner run into an error, sometimes, on certain mode.

A little background, my setup is running Vue 3 using Vite as well as Storybook with Vite builder.

Configurations

jest.config.ts

import type { Config } from "@jest/types";

const config: Config.InitialOptions = {
  preset: "vite-jest",
  testMatch: ["**/src/components/**/*.spec.ts?(x)"],
  testEnvironment: "jest-environment-jsdom",
  collectCoverageFrom: ["**/src/components/**/*.vue"],
  setupFilesAfterEnv: ["<rootDir>/src/jest-setup.ts"],
  watchman: false,
};

export default config;

tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "lib": [
      "esnext",
      "dom",
      "dom.iterable"
    ],
    "allowJs": true,
    "checkJs": true,
    "jsx": "preserve",
    "declaration": true,
    "sourceMap": true,
    "removeComments": true,
    "importHelpers": true,
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
  },
  "typeAcquisition": {
    "enable": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "src/**/*.mdx",
    "src/jest-setup.ts"
  ],
  "exclude": [
    "node_modules",
    ".storybook"
  ]
}

jest-setup.ts

import "@testing-library/jest-dom";

package.json

{
  "name": "design-system",
  "version": "0.0.0",
  "files": [
    "dist"
  ],
  "main": "./dist/my-lib.umd.js",
  "module": "./dist/my-lib.es.js",
  "exports": {
    ".": {
      "import": "./dist/my-lib.es.js",
      "require": "./dist/my-lib.umd.js"
    }
  },
  "scripts": {
    "dev": "vite",
    "storybook": "start-storybook --ci --no-manager-cache -p 6006",
    "storybook:docs": "start-storybook --ci --docs --no-manager-cache -p 6006",
    "lint": "eslint --ignore-path .gitignore .",
    "lint:fix": "eslint --fix --ignore-path .gitignore .",
    "build:library": "vue-tsc --noEmit && vite build",
    "build:storybook": "build-storybook --docs --loglevel verbose --output-dir docs",
    "test": "vite-jest",
    "test:clear": "vite-jest --no-cache",
    "test:watch": "vite-jest --watch ",
    "test:coverage": "vite-jest --coverage",
    "test:debug": "vite-jest --detectOpenHandles",
  },
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@storybook/addon-a11y": "^6.3.0",
    "@storybook/addon-actions": "^6.3.0",
    "@storybook/addon-essentials": "^6.3.0",
    "@storybook/addon-links": "^6.3.0",
    "@storybook/testing-vue3": "0.0.1",
    "@storybook/vue3": "^6.3.0",
    "@tailwindcss/aspect-ratio": "^0.2.1",
    "@tailwindcss/forms": "^0.3.3",
    "@tailwindcss/line-clamp": "^0.2.1",
    "@tailwindcss/typography": "^0.4.1",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/user-event": "^13.1.9",
    "@types/jest": "^26.0.24",
    "@typescript-eslint/eslint-plugin": "^4.28.0",
    "@typescript-eslint/parser": "^4.28.0",
    "@vitejs/plugin-vue": "^1.2.3",
    "@vue/compiler-sfc": "^3.0.5",
    "@vue/eslint-config-prettier": "^6.0.0",
    "@vue/eslint-config-typescript": "^7.0.0",
    "autoprefixer": "^10.2.6",
    "babel-loader": "^8.2.2",
    "eslint": "^7.29.0",
    "eslint-config-prettier": "^6.15.0",
    "eslint-plugin-jest-dom": "^3.9.0",
    "eslint-plugin-mdx": "^1.13.0",
    "eslint-plugin-prettier": "^3.4.0",
    "eslint-plugin-react": "^7.24.0",
    "eslint-plugin-tailwindcss": "^1.13.4",
    "eslint-plugin-vue": "^7.12.1",
    "jest": "^27.0.6",
    "jest-environment-jsdom": "^27.0.6",
    "postcss": "^8.3.5",
    "postcss-preset-env": "^6.7.0",
    "prettier": "^2.3.1",
    "storybook-builder-vite": "^0.0.9",
    "tailwindcss": "^2.2.2",
    "ts-node": "^10.1.0",
    "typescript": "^4.3.4",
    "vite": "^2.3.8",
    "vite-jest": "0.0.2",
    "vue-loader": "^16.2.0",
    "vue-tsc": "^0.0.24"
  },
  "dependencies": {
    "@testing-library/vue": "^6.4.2",
    "vue": "^3.1.2",
    "vue-demi": "^0.9.1"
  },
}

What doesn't works?

When storybook is running, I encounter these errors, for all my test commands.

  ● Test suite failed to run

    Cannot find module '/Users/macOS/Documents/Projects/design-system/node_modules/.vite/@testing-library_jest-dom.js' from 'src/jest-setup.ts'

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)

After I shut down storybook, i ran it again.

npm run test

On first run, I got the same errors as above.

npm run test:watch or npm run test:coverage

    Cannot find module '/Users/macOS/Documents/Projects/design-system/node_modules/.vite/@storybook_testing-vue3.js' from 'src/components/atoms/base-button/base-button.spec.ts'

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)

npm run test:clear

I got these errors, no matter how many times i ran this command.

  ● Base Button › Should not be clickable when loading

    TypeError: userEvent.tab is not a function

What works?

After running npm run test:clear once, I can run the test npm run test:watch or npm run test:coverage but npm run test return this same error above.

    Cannot find module '/Users/macOS/Documents/Projects/design-system/node_modules/.vite/@storybook_testing-vue3.js' from 'src/components/atoms/base-button/base-button.spec.ts'

Cannot find module '/@react-refresh' from 'src/App.tsx'

App.tsx

import React, { useState } from 'react'
import logo from './logo.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Hello Vite + React!</p>
        <p>
          <button type="button" onClick={() => setCount((count) => count + 1)}>
            count is: {count}
          </button>
        </p>
        <p>
          Edit <code>App.tsx</code> and save to test HMR updates.
        </p>
        <p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
          {' | '}
          <a
            className="App-link"
            href="https://vitejs.dev/guide/features.html"
            target="_blank"
            rel="noopener noreferrer"
          >
            Vite Docs
          </a>
        </p>
      </header>
    </div>
  )
}

export default App

Support for SvelteKit projects

As it stands, Vite-Jest has baked in support for React and Vue. See here:

moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'mjs', 'ts', 'tsx'],

Myself and @FractalHQ are working on an "adder" that enables developers to introduce Jest tests to their SvelteKit project. We've recently encountered a similar issue to that faced by Vue and React developers, relating to Jest/Vite nuances. See here:

We've got a similar discussion going on in our repo, relating to us utilising vite-jest in our adder:

The two key points I'd like to address, are the following:

  • What changes would be needed to add svelte support to vite-jest (Relating to transformers, etc)
  • Are there any limitations that prevent us from applying vite-jest to svelte, due to the nature of how .svelte components are created?
  • Would we need to do these changes in co-ordination with another transformer such as svelte-jester to ensure that the .svelte extension is correctly transformed.

Specifying vite config

Is it possible to specify the vite config (in case it is at a non-standard location) through jest.config.js or through the vite-jest command?

Validation error when running vite-jest

When I try to run vite-jest I'm getting this error:

 Validation Error:

  Module /path-to-my-repo/node_modules/vite-jest/index.js in the transform option was not found.
         <rootDir> is: path-to-my-repo

  Configuration Documentation:
  https://jestjs.io/docs/configuration

path-to-my-repo\node_modules\execa\lib\error.js:60
                error = new Error(message);
                        ^

Error: Command failed with exit code 1: node --experimental-vm-modules path-to-my-repo\node_modules\jest\bin\jest.js
    at makeError (path-to-my-repo\node_modules\execa\lib\error.js:60:11)
    at Function.module.exports.sync (path-to-my-repo\node_modules\execa\index.js:194:17)
    at file:///path-to-my-repo/node_modules/vite-jest/bin/vite-jest.js:11:7
    at ModuleJob.run (node:internal/modules/esm/module_job:183:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
    at async handleMainPromise (node:internal/modules/run_main:63:12) {
  shortMessage: 'Command failed with exit code 1: node --experimental-vm-modules path-to-my-repo\\node_modules\\jest\\bin\\jest.js',
  command: 'node --experimental-vm-modules path-to-my-repo\\node_modules\\jest\\bin\\jest.js',
  escapedCommand: 'node --experimental-vm-modules "path-to-my-repo\\node_modules\\jest\\bin\\jest.js"',
  exitCode: 1,
  signal: undefined,
  signalDescription: undefined,
  stdout: undefined,
  stderr: undefined,
  failed: true,
  timedOut: false,
  isCanceled: false,
  killed: false
}

It seems to suggest that vite-jest isn't installed, but it is so I'm kind of at a loss

import.meta compatibility

It looks like vite-jest is not able to correctly handle accessing import.meta.env in components. I cloned the react-app-ts example and tried to use an env variable. However, I ended up with the "Invalid hook call" error.

image

image

Without import.meta.env, the tests passed successfully. Considering the fact that Vite is using import.meta for a few things, I think it would be great if vite-jest was able to process it.

Alias config

Just trying to get aliases working and I can't seem to figure it out. I have tried any combination of jest.config.js as well as vite.config.js, you can see my commit here

jest.config.js

export default {
  preset: 'vite-jest',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
  testMatch: [
    '<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}',
    '<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}',
  ],
  testEnvironment: 'jest-environment-jsdom'
}

vite.config.js

import path from 'path'
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [...(process.env.NODE_ENV !== 'test' ? [reactRefresh()] : [])],
  resolve: {
    alias: {
      '@': path.join(path.resolve('./src'))
    }
  }
})

Is it currently possible in vite-jest?

A way to include dependencies for dev server in optimizeDeps to find everything first run

I had problems with vite-jest not finding all dependencies the first run until I realised that you have to have the dev server include them in optimizeDeps. Otherwise, it may take a few runs for vite to pick them up. I ended up moving the vite-jest code base into my project to get around this.

My question is - is there a good way that we can change the vite-jest code to make the dev server, vite-server.js inside of vite-jest easily configurable?

Is there any solution to use vite-jest for an application which using Vite + Vue2 + Composition API?

If Vite + Vue2 is not vite-jest support target, I'll close this issue.

I got this error when I run vite-jest

$ ./node_modules/.bin/vite-jest
(node:16061) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Determining test suites to run...Pre-bundling dependencies:
  @vue/composition-api
  ....
  (...and 56 more)
(this will be run only when your dependencies or config have changed)
 > node_modules/@vue/composition-api/dist/vue-composition-api.esm.js:1:16: error: Could not read from file: /home/me/vite-vu2-app/vue/dist/vue.esm-bundler.js
    1 │ import Vue from 'vue';
      ╵                 ~~~~~

Error: Build failed with 1 error:
node_modules/@vue/composition-api/dist/vue-composition-api.esm.js:1:16: error: Could not read from file: /home/me/vite-vu2-app/vue/dist/vue.esm-bundler.js
    at failureErrorWithLog (/home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:1493:15)
    at /home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:1151:28
    at runOnEndCallbacks (/home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:941:63)
    at buildResponseToResult (/home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:1149:7)
    at /home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:1258:14
    at /home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:629:9
    at handleIncomingPacket (/home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:726:9)
    at Socket.readFromStdout (/home/me/vite-vu2-app/node_modules/esbuild/lib/main.js:596:7)
    at Socket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10)
    at Pipe.onStreamRead (node:internal/stream_base_commons:199:23)

My environment

$ node --version
v16.13.0
$ jq .version node_modules/vite/package.json
"2.7.7"
$ jq .version node_modules/vue/package.json
"2.6.14"
$ jq .version node_modules/@vue/composition-api/package.json
"1.0.4"
$ grep preset jest.config.js
  preset: "vite-jest",

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.