Repository navigation
Description
(previously...)
Making an issue to track work on the Jest experience with vite.
Jest is a very popular JavaScript testing framework. Some standout features:
- Support for mocking functions and modules
- Parallelisation and prioritisation of tests
- Snapshot tests
- Running only changed tests between 2 revisions (or based on a set of files)
It would be worthy to provide some form of blessed integration to use with vite.
(If you don't need these features, you may be better off using a testing framework like uvu, which should be much simpler to setup.)
- Files could be transformed with
esbuildto make jest tests startup and run faster (prior art:esbuild-jest,esbuild-jest-transform). - Files could share the same transforms that
vitealready uses for newer syntax (for example, support forimport.metaviababel-plugin-transform-import-meta) untiljestships full support for ES modules. - Files could have
jest.mock()calls hoisted above imports withbabel-plugin-jest-hoist(explanation) until top-levelawaitlands fully inesbuild, at which point you could codemod all tests to use tla imports, and remove thebabelplugin. (This still requires support fromjestfor ES modules, or else it won't detect tests defined after a couple of ticks have passed.)- This exists as an
swcpackage too, which is very appealing (via vite#788).
- This exists as an
- I think
jestusesbabel-plugin-istanbulfor coverage. This may never land inesbuild.
@yyx990803 mentioned spinning up a ViteDevServer and using vite.transformRequest() as the transform. One problem here is that the jest transform is expected to be synchronous. Jest's likely going to fix this as part of the ES module work, tracking here. (Further, it's not clear to me what the devx would be? Should we run a vite server in a seaparate process/terminal tab? Or should we introduce a vite test command that wraps jest?
Let me propose a first step: in my own repo I'm going to do the bare minimum: esbuild-jest (possibly modified) + babel-plugin-transform-import-meta + babel-plugin-jest-hoist + babel-plugin-istanbul. Anything I'm missing? What are the vite specific bits to inject into the environment? Discuss!
Activity
yyx990803 commentedon Feb 9, 2021
The main issue I see for not leveraging Vite itself for the transforms is that you won't get Vite plugin compatibility in Jest - e.g. if you add a Vite plugin that does some custom transforms, it won't apply to the Jest files. So this would still require Jest-specific transforms for e.g. Vue or Svelte files. I think your approach would work for J/TSX-only projects but not all Vite projects.
Another aspect of this is Vite configured alias and defines - they'd be automatically covered if the files are transformed by Vite, but you'd have to manually read the config and replicate them in your setup.
The ideal situation is to let Vite transform the files to how they'd run in Node (reusing part of the SSR transform logic), but Jest requiring transforms to be synchronous seems to be a major blocker here. Judging from jestjs/jest#9504 it seems there isn't much progress on this front :/
threepointone commentedon Feb 9, 2021
Yeah this has been running around my mind as well.
One idea I had, because it's all so fast, is to just do a build (without minification and concatenation) and have jest operate on that. 🤔
threepointone commentedon Feb 9, 2021
The PR for jest's async transform support jestjs/jest#9889
threepointone commentedon Feb 10, 2021
Ok I think I have ideas for hackzz. I'm going to try some stuff out, as and when I have time in the evenings. Will get back to this thread this weekend.
nathanforce commentedon Feb 10, 2021
@threepointone I've been playing with this concept using
esbuildfor a little while. I'd be happy to compare notes if you'd like. Here's an example of what my tests look like.That repo is a repro for a leak issue so it is stripped of anything non-essential, but the same pattern could be used in jest/ava/uvu.
mpeyper commentedon Feb 27, 2021
Just for anyone looking for something for right now, we wrote a (probably naive) Babel plugin that handles
import.meta.env,import.meta.glob(...)andimport.meta.globEager(...)transforms for ourjesttests. I'm not sure what other custom transformsvitehas, but this is what we needed for our project.We have discussed extracting this into a stand alone package and publishing it if there is any interest in others using it.
JacobMGEvans commentedon Feb 27, 2021
Was needed for enabling our Orgs OSS contributing to a Vite project since a majority of our group is familiar with Jest it seemed worth the extra effort!
It is now successfully running Jest + React Testing Library, locally and in GH actions
mpeyper commentedon Mar 11, 2021
We ended up cleaning it up a bit and publishing it to NPM (source code).
xiaoxiangmoe commentedon Mar 17, 2021
@yyx990803 async code transformations are implemented by jestjs/jest#11191 and it was released in jest 27.0.0-next.5
axe-me commentedon Mar 31, 2021
I'm trying to write a vite jest preset recently. Now I got a blocker, that I need jest to allow async resolver to allow vite to do module resolving. see jestjs/jest#11226 (comment) and jestjs/jest#9505
Without a custom resolver, features like virtual ID, etc won't work.
haoqunjiang commentedon Mar 31, 2021
FYI I've just implemented a super hacky vite-jest transformer with ViteDevServer.
The implementation
https://github.com/sodatea/vite-jest/tree/main/packages/vite-jest
A working example:
https://github.com/sodatea/vite-jest/tree/main/examples/vue-app-type-module
2 main hacks used in the implementation:
moduleNameMapperto fix injected paths from Vite core plugins (adding aliases of/@vite/clientand/@vite/env) and a simple regular expression replacement in the transformer implementation to support@fsURLs.transformIgnorePatternalso needs to be fine-tuned.And I have to patch Vite (https://github.com/sodatea/vite-jest/blob/main/examples/vue-app-type-module/patch-vite.js) to rename
client.js&env.jsto use the.mjsextension, so that they can be recognized by Node.js as ES modules.ianschmitz commentedon Mar 31, 2021
For those of us unfamiliar with Vite, why is it necessary to spin up the
ViteDevServerto facilitate Jest testing? Requiring a recent version of Node and ESM support in Jest makes sense to me, but beyond those requirements how is it different from any other Node project (similar to #1149)? Is it that we're trying to avoid bringing in babel in favor of esbuild to keep consistency between dev/test env?haoqunjiang commentedon Apr 1, 2021
@ianschmitz
Yeah, it's for simplicity and consistency. Setting up Jest using
esbuild-jestand other packages kinda works for now.But like Evan has said earlier, to support other custom transformations, such as
.svelteand.vuefiles, andimport.meta.extensions (import.meta.env,import.meta.glob, etc.), Jest used to require additional transformers like vue-jest.That's a lot of overcomplication.
We are basically duplicating all the transformation logic in Jest transformers again (and the configurations). And it's hard to make sure the behaviors are consistent between these implementations.
If we can spin up a
ViteDevServerand make the Jest resolver/transformer simply proxy all the requests to that server, life would be so much easier.30 remaining items
fadi-george commentedon Dec 8, 2021
Regarding
import.meta, youd just need something like this for your babel config:e.g.
IanVS commentedon Dec 10, 2021
While we wait for movement from jest to provide better support for projects like vite, I've created an example repo which shows how to use some of the best parts of jest (like its
expectassertions andjest.fn()mocks) together with @web/test-runner to run unit tests in a headless browser: https://github.com/IanVS/vite-testing-example.This approach has been working well for me so far, with 143 tests (including many react component tests) across 46 test suites running in three headless browsers (chromium, firefox, and safari) in ~35 seconds.
charles-allen commentedon Dec 11, 2021
In the meantime, you might want to keep track of https://vitest.dev/
BenjaBobs commentedon Dec 23, 2021
For those following this thread, https://github.com/vitest-dev/vitest just opened.
mquandalle commentedon Jan 25, 2022
I think Vitest solves this issue?
mazerty commentedon Jan 25, 2022
not really, but it is an interesting alternative indeed :)
wandarkaf commentedon Feb 4, 2022
Maybe I can share my experience blending vite with jest. I hope everyone can find it helpful or at least insightful.
The only thing that worked for me was vite-jest, which is still a work in progress., as mentioned by @sodatea. But the approach works on macOS. Here's how to configure your project to run the
Jesttest successfully. In my case is more focused onVue, but I think areacttransition could be easy to make:package.json
{ // your configuration... "type": "module", "scripts": { // your scripts... "test:unit": "vite-jest --no-cache", }, "devDependencies": { // your dev dependencies... "@vue/test-utils": "^2.0.0-rc.18", "jest": "^27.4.7", "jest-environment-jsdom": "^27.4.6", "vite-jest": "^0.1.4", } }jest.config.js
vite.config.js
One thing to notice, and pretty important, is that your app will work on
type: modulemode. So it is good to know that we will need to tweak our project to work in that mode, i.e., no morerequireormodule.exporton your code, to mention a few.I hope it helps those who want to work with
JestandViteat the moment.owen26 commentedon Feb 4, 2022
I might be able to share some of my experiences with Vite + React + Jest.
At the moment there is no perfect built-in solution indeed. And I'm hesitate to use a tool that is still considered WIP for our production project (e.g.
vite-jest)So what I did is basically write a jest config from scratch with a minimum 3rd party helper, in my case, this is the good old
ts-jest.The complete config file is straightforward.
To solve the stylesheet importing issue, add module mapper and proxy them to
identity-obj-proxyaccordingly.To solve SVG importing issue, add a mock file mapper
then in the mapper do whatever fits your SVG transformation rules. In my case I love the
create-react-appconvention so what I need isTo solve the customized tsconfig
pathissue, simply do the same mapping to redirect them to the correct path.To resolve
import.metaissue, this is a bit tricky cuz I want to limit the usage of Babel under-the-hood for magical transformation, so instead, I decided to make my code better in a sense that thoseimport.metausage can be easily mocked.I put all
import.metain a single fileconfig.tsThen in Jest I just mock the config file via
setupTest.ts, to avoid having to polyfillimport.metajensbodal commentedon Mar 18, 2022
Shouldn'tsetupFilesAfterEnv: ['./src/setupTests.ts']besetupFilesAfterEnv: './src/setupTests.ts'?EDIT: I quoted the wrong one, I meant shouldn't
'^.+\\.(t|j)sx?$': ['ts-jest'],be'^.+\\.(t|j)sx?$': 'ts-jest',?BenShelton commentedon Mar 18, 2022
No, it should be an array. See https://jestjs.io/docs/configuration#setupfilesafterenv-array
jensbodal commentedon Mar 18, 2022
Sorry I commented on the wrong one, I meant
ts-jestshould be a stringpatak-cat commentedon Mar 19, 2022
I think we can close this issue now that vite-jest is available. Check the last comment from @sodatea here. I don't see further steps to be taken in Vite Core. Please create more focused issues in the proper repository (vite, jest, or vite-jest) moving forward.
As a note, Vitest is also now available as an alternative to Jest.
jensbodal commentedon Mar 19, 2022
I didn’t like the idea of having to spin up the vite server for testing. I’ve currently got this working with es-build so I guess I’ll just post my config for posterity’s sake.
jest.config.tssetup-files-globals.tssvg-transform.jssetup-files-mocks.tssetup-files-after-env.tsThe mock for
import.meta.env.VITE_BUILD_COMMITonly seemed necessary once I collated them to a constants file. But I’m fine with that setup.