Giter VIP home page Giter VIP logo

vitest's Introduction

Vitest

Next generation testing framework powered by Vite.

Get involved!

Documentation | Getting Started | Examples | Why Vitest?

中文文档



Features

Vitest 1.0 requires Vite >=v5.0.0 and Node >=v18.0.0

import { assert, describe, expect, it } from 'vitest'

describe('suite name', () => {
  it('foo', () => {
    expect(1 + 1).toEqual(2)
    expect(true).to.be.true
  })

  it('bar', () => {
    assert.equal(Math.sqrt(4), 2)
  })

  it('snapshot', () => {
    expect({ foo: 'bar' }).toMatchSnapshot()
  })
})
$ npx vitest

Sponsors

Vladimir Sponsors

Anthony Fu Sponsors

Patak Sponsors

Credits

Thanks to:

Contribution

See Contributing Guide.

License

MIT License © 2021-Present Anthony Fu, Matias Capeletto

vitest's People

Contributors

11joselu avatar antfu avatar ariperkkio avatar aslemammad avatar btea avatar cexbrayat avatar dammy001 avatar demivan avatar deryeger avatar dominikg avatar dsyddall avatar dunqing avatar edimitchel avatar fenghan34 avatar g4rry420 avatar hi-ogawa avatar nieyuyao avatar patak-dev avatar poyoho avatar renovate[bot] avatar sapphi-red avatar saul-mirone avatar sheremet-va avatar simon-abbott avatar so1ve avatar togami2864 avatar tony-go avatar userquin avatar wtchnm avatar zxch3n 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  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

vitest's Issues

Watch mode (dev mode) by default

I think the DX of watch mode is great already. For most of the time, we are using test tools to do try-and-error in developement. I think it makes sense to make it just like Vite, to be dev first.

  • vitest -> watch mode in TTY, one time run in CI
  • vitest run -> one time run
  • vitest dev / vitest watch -> watch mode

Make `jsdom` and `happy-dom` peerDeps

In the last refactoring of env, I already made the import for them dynamic. Now we just need to move the deps, update examples, and properly document it.

Custom matchers with auto definition types

For some custom needs, special matcher are needed.
expect from jest provides an extend method for doing that.
Jasmine is also able to do it.

There is something common between both solutions which Vitest can improve: generate the type definition automatically.

So being able to add our custom matchers, and then, get automatically the type globally either by a definition type file put in the source code or by a type put in cache somewhere in node_modules of Vitest which would be taken in order by typescript on test files.

Support nested "describe" block

It's pretty common to group your test with "nested describe block" but while testing vitest found that it doesn't work with nested describe block.

import { describe, it, expect } from "vitest";

describe("top level describe", () => {
  it("this work", () => {
    expect(true).toBe(true);
  });

  describe("nested describe", () => {
    it("this is ignore", () => {
      expect(true).toBe(true);
    });
  });
});

The nested block is just ignored

image

If you want to send PR

Leave a comment below so I can give you permission to push a branch in this repo. Sorry, this has to be manual since the permission control in free GitHub org is very limited. Thanks!

When doing PR, please do NOT commit directly to main branch. Please create branch follow <your-gh-id>/<short-describe> and push your change to the branch to send PR. For example: antfu/fix-typo or patak/feat-concurrent-mode. Thanks

Coverage

@antfu creating an issue to be able to leave some links here. I won't be able to implement this myself, but I checked a bit what is needed and maybe some of these notes end up being useful.

Jest implements coverage using babel, but it can use v8 as an experimental provide. Given that native v8 code coverage is a lot faster, and that in newer versions of node it should work well, I think that vitest should use native v8 coverage directly.

This is the PR where v8 coverage was added to Jest jestjs/jest#8596

There are a few libs that were created as part of this process

There seems to be a merging needed of the generated reports, and there are a few libs to merge both the V8 format and the Istanbul format. I wonder if there is a way to generate the report without bringing Istanbul here

Dependencies in vitest/node_modules are not pre-bundled by vite

I found that I already had a version of jest-util in my project from another dependency, so npm had to put vitest's version inside vitest/node_modules/jest-util, but vite does not pre-bundle this, and so an import of the commonjs dependency results in:

ReferenceError: exports is not defined
    at /Users/ianvs/code/defined/webclient/node_modules/vitest/node_modules/jest-util/build/index.js:3:23

See https://stackblitz.com/edit/vite-ftqpuj?file=example.test.js for a reproduction of the issue.

Inline deps

  • elegant-spinner
  • cli-truncate
  • log-symbols
  • figures
  • jest-snapshot @antfu
  • jest-util

__vite_ssr_import_2__.format is not a function

I'm trying to switch my project to Vitest, but sadly it fails in almost all tests with TypeError: __vite_ssr_import_2__.format is not a function, were format is from the devDependency prettier. (import { format } from 'prettier';)

image

TypeError: __vite_ssr_import_2__.format is not a function
/home/shinigami/OpenSource/Shinigami92/plugin-pug/tests/issues/issue-24/issue-24.test.ts:11:25
9  |            const expected: string = readFileSync(resolve(__dirname, 'formatted.pug'), 'utf8');
10 |            const code: string = readFileSync(resolve(__dirname, 'unformatted.pug'), 'utf8');
11 |            const actual: string = format(code, { parser: 'pug', plugins: [plugin] });
   |                           ^
12 |  
13 |            expect(actual).toBe(expected);

prettier/plugin-pug#319

https://github.com/prettier/plugin-pug/runs/4492780914?check_suite_focus=true#step:9:587

I already tried something like:

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

export default defineConfig({
	test: {
		deps: {
			// Only `external` or only `inline` or both together
			external: ['prettier'],
			inline: ['prettier']
		}
	}
});

Depending of the config, it throws different errors, but it doesn't work.

I assume it has something to do with that prettier is a devDependency or maybe in "wrong" format?! cjs/mjs stuff like that?

Enhanced watch mode

Can be switched between multiple rerun strategies:

  • Smart mode
  • Filter by string or RegExp
  • Run all

[Windows] `__dirname` is prepended with a `/`

So, I've got a Node/TS project which unit test suite was using uvu, and I'm migrating it to vitest to try it out.
In one of my tests, I have the following:

const presetPath = path.resolve(__dirname, './fixtures/basic-preset.ts')
const preset = await importPresetFile(presetPath)

There is an issue with __dirname there, it returns /D:/Code/projects/preset/preset/packages/core/test instead of D:/Code/projects/preset/preset/packages/core/test (there is a leading /).

This leads to another error where I can't import the preset (using egoist/bundle-require, not sure if relevant here).

Full trace
➜  p vitest import

Vitest is currently in closed beta exclusively for Sponsors
Become a Sponsor of https://github.com/sponsors/patak-js or https://github.com/sponsors/antfu 
to access the source code and issues tracker 💖

Running tests under D:\Code\projects\preset\preset\packages\core

  preset:core:import /D:/Code/projects/preset/preset/packages/core/test D:\D:\Code\projects\preset\preset\packages\core\test\fixtures\basic-preset.ts +0ms
  preset:core:import Importing "D:\D:\Code\projects\preset\preset\packages\core\test\fixtures\basic-preset.ts" with bundle-require." +0ms
  > test\import.test.ts
    \ typescript presets can be imported
  > test\import.test.ts
    × typescript presets can be imported
      → error: Could not resolve "D:\\D:\\Code\\projects\\preset\\preset\\packages\\core\\test\\fixtures\\basic-preset.ts"


Failed Tests (1)

✖  FAIL  typescript presets can be imported
Error: Build failed with 1 error:
error: Could not resolve "D:\\D:\\Code\\projects\\preset\\preset\\packages\\core\\test\\fixtures\\basic-preset.ts"
    at failureErrorWithLog (D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1493:15)
    at D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1151:28
    at runOnEndCallbacks (D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:941:63)
    at buildResponseToResult (D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1149:7)
    at D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1258:14
    at D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:629:9
    at handleIncomingPacket (D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:726:9)
    at Socket.readFromStdout (D:\Code\projects\preset\preset\packages\core\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:596:7)
    at Socket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12) {
  errors: [
    {
      detail: undefined,
      location: null,
      notes: [],
      pluginName: '',
      text: 'Could not resolve "D:\\\\D:\\\\Code\\\\projects\\\\preset\\\\preset\\\\packages\\\\core\\\\test\\\\fixtures\\\\basic-preset.ts"'
    }
  ],
  warnings: []
}

Passed   0 / 1
Failed   1 / 1
Time     737.49ms

The filepath given to bundleRequire is simply presetPath, shown in the first snippet, so the path with the leading /. When manually removing the leading / and trying to import my TypeScript file with bundleRequire, everything works as expected.

I tried patching https://github.com/antfu-sponsors/vitest/blob/36604be3496eaa6949443138b93310fdc7310ae1/src/node/node.ts#L96 but it doesn't work either, given how Vite works:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'd:'
    at new NodeError (node:internal/errors:371:5)
    at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:1016:11)
    at Loader.resolve (node:internal/modules/esm/loader:89:40)
    at Loader.getModuleJob (node:internal/modules/esm/loader:242:28)
    at Loader.import (node:internal/modules/esm/loader:177:28)
    at importModuleDynamically (node:internal/modules/esm/translators:115:35)
    at exports.importModuleDynamicallyCallback (node:internal/process/esm_loader:30:14)
    at cachedRequest (file:///D:/Code/projects/preset/preset/packages/core/node_modules/.pnpm/[email protected][email protected]/node_modules/vitest/dist/node/node.js:137:13)
    at request (file:///D:/Code/projects/preset/preset/packages/core/node_modules/.pnpm/[email protected][email protected]/node_modules/vitest/dist/node/node.js:104:20)
    at D:/Code/projects/preset/preset/packages/core/node_modules/.pnpm/[email protected][email protected]/node_modules/vitest/dist/run/index.js:1:196 {
  code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
}

So, not exactly sure how to fix this. Maybe it's just a matter of properly configuring vite.config.ts?

[Feature Request] Add option to disable the use of atomics in Piscina.js

I have played around with Vitest a bit on StackBlitz and it's really nice! Great work 👏

However, I have noticed you are using Piscina.js which uses an API which is currently unsupported in WebContainer, but I am working on an MVP to enable this API, namely receiveMessageOnPort. But our team has submitted a PR to Piscina.js for the time being that allows to disable the use of Atomics with an env flag (PISCINA_DISABLE_ATOMICS ). Piscina.js also supports disabling atomics when providing a config. The option is called useAtomics.

I would suggest to introduce a similar option for Vitest that transitively disables atomics for Piscina.js. I think this can be useful not only because it currently doesn't work in WebConrtainer.

If you want my help, I could also submit a PR.

Feature request: setup file

Hey! Thanks for the great work so far! Loving it!
I'm trying to use vitest in my toy project and I'm missing something like setupFilesAfterEnv so much 😢
I will be happy to make a PR if you can provide me with some guidance.

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.