Skip to content

feature: first class Jest integration #1955

Closed

Description

@threepointone

(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.)

@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

  1. yyx990803 commented on Feb 9, 2021

    @yyx990803
    Member

    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 :/

  2. threepointone commented on Feb 9, 2021

    @threepointone
    ContributorAuthor

    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. 🤔

  3. threepointone commented on Feb 9, 2021

    @threepointone
    ContributorAuthor

    The PR for jest's async transform support jestjs/jest#9889

  4. threepointone commented on Feb 10, 2021

    @threepointone
    ContributorAuthor

    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.

  5. nathanforce commented on Feb 10, 2021

    @nathanforce

    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 I've been playing with this concept using esbuild for 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.

  6. mpeyper commented on Feb 27, 2021

    @mpeyper

    Just for anyone looking for something for right now, we wrote a (probably naive) Babel plugin that handles import.meta.env, import.meta.glob(...) and import.meta.globEager(...) transforms for our jest tests. I'm not sure what other custom transforms vite has, 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.

  7. JacobMGEvans commented on Feb 27, 2021

    @JacobMGEvans

    Just for anyone looking for something for right now, we wrote a (probably naive) Babel plugin that handles import.meta.env, import.meta.glob(...) and import.meta.globEager(...) transforms for our jest tests. I'm not sure what other custom transforms vite has, 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.

    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

  8. mpeyper commented on Mar 11, 2021

    @mpeyper

    Just for anyone looking for something for right now, we wrote a (probably naive) Babel plugin that handles import.meta.env, import.meta.glob(...) and import.meta.globEager(...) transforms for our jest tests. I'm not sure what other custom transforms vite has, 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.

    We ended up cleaning it up a bit and publishing it to NPM (source code).

  9. xiaoxiangmoe commented on Mar 17, 2021

    @xiaoxiangmoe
    Contributor

    @yyx990803 async code transformations are implemented by jestjs/jest#11191 and it was released in jest 27.0.0-next.5

  10. axe-me commented on Mar 31, 2021

    @axe-me
    Contributor

    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.

  11. haoqunjiang commented on Mar 31, 2021

    @haoqunjiang
    Member

    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:

    1. Implemented a custom reporter to close the Vite server after test completion.
    2. As Jest does not support async resolver at the moment, I have to use a combination of moduleNameMapper to fix injected paths from Vite core plugins (adding aliases of /@vite/client and /@vite/env) and a simple regular expression replacement in the transformer implementation to support @fs URLs. transformIgnorePattern also 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.js to use the .mjs extension, so that they can be recognized by Node.js as ES modules.

  12. ianschmitz commented on Mar 31, 2021

    @ianschmitz

    For those of us unfamiliar with Vite, why is it necessary to spin up the ViteDevServer to 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?

  13. haoqunjiang commented on Apr 1, 2021

    @haoqunjiang
    Member

    @ianschmitz

    Yeah, it's for simplicity and consistency. Setting up Jest using esbuild-jest and other packages kinda works for now.

    But like Evan has said earlier, to support other custom transformations, such as .svelte and .vue files, and import.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 ViteDevServer and make the Jest resolver/transformer simply proxy all the requests to that server, life would be so much easier.

  14. 30 remaining items

  15. fadi-george commented on Dec 8, 2021

    @fadi-george

    Regarding import.meta, youd just need something like this for your babel config:

     function () {
        return {
          visitor: {
            MetaProperty(path) {
              path.replaceWithSourceString('process');
            },
          },
        };
      },
    

    e.g.

    module.exports = {
      env: {
        test: {
          plugins: [
            function () {
              return {
                visitor: {
                  MetaProperty(path) {
                    path.replaceWithSourceString('process');
                  },
                },
              };
            },
          ],
          presets: [
            ['@babel/preset-env', { targets: { node: 'current' } }],
            '@babel/preset-typescript',
            [
              '@babel/preset-react',
              {
                runtime: 'automatic',
              },
            ],
          ],
        },
      },
    };
    
  16. IanVS commented on Dec 10, 2021

    @IanVS
    Contributor

    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 expect assertions and jest.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.

  17. charles-allen commented on Dec 11, 2021

    @charles-allen

    In the meantime, you might want to keep track of https://vitest.dev/

  18. BenjaBobs commented on Dec 23, 2021

    @BenjaBobs

    For those following this thread, https://github.com/vitest-dev/vitest just opened.

  19. mquandalle commented on Jan 25, 2022

    @mquandalle

    I think Vitest solves this issue?

  20. mazerty commented on Jan 25, 2022

    @mazerty

    not really, but it is an interesting alternative indeed :)

  21. wandarkaf commented on Feb 4, 2022

    @wandarkaf

    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 Jest test successfully. In my case is more focused on Vue, but I think a react transition 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

    export default {
      preset: 'vite-jest',
      testMatch: [
        '**/tests/unit/**/*.spec.?(m)js?(x)',
        '**/__tests__/*.?(m)js?(x)',
      ],
      testEnvironment: 'jest-environment-jsdom',
    }

    vite.config.js

    import { fileURLToPath } from 'url'
    
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [vue()],
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url)),
        },
      },
    })

    One thing to notice, and pretty important, is that your app will work on type: module mode. So it is good to know that we will need to tweak our project to work in that mode, i.e., no more require or module.export on your code, to mention a few.

    I hope it helps those who want to work with Jest and Vite at the moment.

  22. owen26 commented on Feb 4, 2022

    @owen26

    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.

    module.exports = {
      preset: 'ts-jest',
      testEnvironment: 'jsdom',
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
      moduleNameMapper: {
        '^~/(.*)$': '<rootDir>/src/$1',
        '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
        '\\.svg$': '<rootDir>/__mocks__/svg-mock.js',
      },
      transform: {
        '^.+\\.(t|j)sx?$': ['ts-jest'],
      },
      setupFilesAfterEnv: ['./src/setupTests.ts'],
    };

    To solve the stylesheet importing issue, add module mapper and proxy them to identity-obj-proxy accordingly.

    '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
    

    To solve SVG importing issue, add a mock file mapper

    '\\.svg$': '<rootDir>/__mocks__/svg-mock.js',
    

    then in the mapper do whatever fits your SVG transformation rules. In my case I love the create-react-app convention so what I need is

    export default 'SvgrURL';
    export const ReactComponent = 'div';
    

    To solve the customized tsconfig path issue, simply do the same mapping to redirect them to the correct path.

    '^~/(.*)$': '<rootDir>/src/$1',
    

    To resolve import.meta issue, 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 those import.meta usage can be easily mocked.

    I put all import.meta in a single file config.ts

    const FOO = import.meta.env.FOO;
    const BAR = import.meta.env.BAR;
    
    export const APP_CONFIG = { FOO, BAR };
    

    Then in Jest I just mock the config file via setupTest.ts, to avoid having to polyfill import.meta

    jest.mock('~/config', () => {
      return { APP_CONFIG: { FOO: 'foo', BAR: 'bar' } };
    });
    
  23. jensbodal commented on Mar 18, 2022

    @jensbodal
      preset: 'ts-jest',
      testEnvironment: 'jsdom',
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
      moduleNameMapper: {
        '^~/(.*)$': '<rootDir>/src/$1',
        '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
        '\\.svg$': '<rootDir>/__mocks__/svg-mock.js',
      },
      transform: {
        '^.+\\.(t|j)sx?$': ['ts-jest'],
      },
      setupFilesAfterEnv: ['./src/setupTests.ts'],

    Shouldn't setupFilesAfterEnv: ['./src/setupTests.ts'] be setupFilesAfterEnv: './src/setupTests.ts'?

    EDIT: I quoted the wrong one, I meant shouldn't '^.+\\.(t|j)sx?$': ['ts-jest'], be '^.+\\.(t|j)sx?$': 'ts-jest',?

  24. BenShelton commented on Mar 18, 2022

    @BenShelton
      preset: 'ts-jest',
      testEnvironment: 'jsdom',
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
      moduleNameMapper: {
        '^~/(.*)$': '<rootDir>/src/$1',
        '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
        '\\.svg$': '<rootDir>/__mocks__/svg-mock.js',
      },
      transform: {
        '^.+\\.(t|j)sx?$': ['ts-jest'],
      },
      setupFilesAfterEnv: ['./src/setupTests.ts'],

    Shouldn't setupFilesAfterEnv: ['./src/setupTests.ts'] be setupFilesAfterEnv: './src/setupTests.ts'?

    No, it should be an array. See https://jestjs.io/docs/configuration#setupfilesafterenv-array

  25. jensbodal commented on Mar 18, 2022

    @jensbodal

    Sorry I commented on the wrong one, I meant

        '^.+\\.(t|j)sx?$': ['ts-jest'],
    

    ts-jest should be a string

  26. patak-cat commented on Mar 19, 2022

    @patak-cat
    Member

    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.

  27. jensbodal commented on Mar 19, 2022

    @jensbodal

    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.ts

    import { get } from 'alias-hq';
    
    import type { Config } from '@jest/types';
    
    const config: Config.InitialOptions = {
      displayName: 'web',
      extensionsToTreatAsEsm: ['.ts', '.tsx'],
      coveragePathIgnorePatterns: ['^.*/constants/.*$'],
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
      moduleNameMapper: get('jest'),
      preset: '../../jest.preset.js',
      setupFiles: [
        '<rootDir>/scripts/test/setup-files-globals.ts', 
        '<rootDir>/scripts/test/setup-files-mocks.ts'
      ],
      setupFilesAfterEnv: ['<rootDir>/scripts/test/setup-files-after-env.ts'],
      transform: {
        '^.+\\.[tj]sx?$': 'esbuild-jest',
        '^.+\\.svg$': '<rootDir>/scripts/test/svg-transform.js',
      },
      transformIgnorePatterns: ['node_modules/(?!internalPackageThatExportsEsm|ky)'],
    };
    
    // eslint-disable-next-line import/no-default-export
    export default config;
    

    setup-files-globals.ts

    import fetch, { Headers, Request, Response } from 'cross-fetch';
    import React from 'react';
    
    global.fetch = fetch;
    global.React = React;
    global.Headers = Headers;
    global.Request = Request;
    global.Response = Response;
    

    svg-transform.js

    module.exports = {
      process() {
        return 'module.exports = {};';
      },
      getCacheKey() {
        // The output is always the same.
        return 'svgTransform';
      },
    };
    

    setup-files-mocks.ts

    const environment = {
      VITE_BUILD_COMMIT: 'mockBuildCommit',
    };
    
    jest.mock('../../src/constants/environment', () => environment);
    

    setup-files-after-env.ts

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

    The mock for import.meta.env.VITE_BUILD_COMMIT only seemed necessary once I collated them to a constants file. But I’m fine with that setup.

  28. locked and limited conversation to collaborators on Apr 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions