From f367f0b3038c0430fc51fd634d63a6db80efa52c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?W=C3=A1ng=20W=C4=9Bi=20T=C4=81o?= Date: Fri, 3 Nov 2023 05:01:36 +0000 Subject: [PATCH] docs(cn): conflict resolution --- .vitepress/config.ts | 61 -- .vitepress/style/vars.css | 26 +- api/expect.md | 1163 +++---------------------------------- api/index.md | 852 +++++---------------------- config/index.md | 26 +- guide/migration.md | 23 +- guide/snapshot.md | 12 +- index.md | 19 +- package.json | 5 +- pnpm-lock.yaml | 9 + 10 files changed, 255 insertions(+), 1941 deletions(-) diff --git a/.vitepress/config.ts b/.vitepress/config.ts index 18fb63aa..8ecda97d 100644 --- a/.vitepress/config.ts +++ b/.vitepress/config.ts @@ -35,7 +35,6 @@ export default withPwa( link: 'https://vitest.dev/', }, }, -<<<<<<< HEAD head: [ ['meta', { name: 'theme-color', content: '#729b1a' }], ['link', { rel: 'icon', href: '/favicon.ico', sizes: 'any' }], @@ -54,66 +53,6 @@ export default withPwa( ['noscript', {}, ``], ['link', { rel: 'mask-icon', href: '/logo.svg', color: '#ffffff' }], ['link', { rel: 'apple-touch-icon', href: '/apple-touch-icon.png', sizes: '180x180' }], -======= - zh: { - label: '简体中文', - lang: 'zh', - link: 'https://cn.vitest.dev/', - }, - }, - head: [ - ['meta', { name: 'theme-color', content: '#729b1a' }], - ['link', { rel: 'icon', href: '/favicon.ico', sizes: 'any' }], - ['link', { rel: 'icon', href: '/logo.svg', type: 'image/svg+xml' }], - ['meta', { name: 'author', content: `${teamMembers.map(c => c.name).join(', ')} and ${vitestName} contributors` }], - ['meta', { name: 'keywords', content: 'vitest, vite, test, coverage, snapshot, react, vue, preact, svelte, solid, lit, marko, ruby, cypress, puppeteer, jsdom, happy-dom, test-runner, jest, typescript, esm, tinypool, tinyspy, node' }], - ['meta', { property: 'og:title', content: vitestName }], - ['meta', { property: 'og:description', content: vitestDescription }], - ['meta', { property: 'og:url', content: ogUrl }], - ['meta', { property: 'og:image', content: ogImage }], - ['meta', { name: 'twitter:title', content: vitestName }], - ['meta', { name: 'twitter:description', content: vitestDescription }], - ['meta', { name: 'twitter:image', content: ogImage }], - ['meta', { name: 'twitter:card', content: 'summary_large_image' }], - ['link', { rel: 'preload', as: 'style', onload: 'this.onload=null;this.rel=\'stylesheet\'', href: font }], - ['noscript', {}, ``], - ['link', { rel: 'mask-icon', href: '/logo.svg', color: '#ffffff' }], - ['link', { rel: 'apple-touch-icon', href: '/apple-touch-icon.png', sizes: '180x180' }], - ], - lastUpdated: true, - markdown: { - theme: { - light: 'github-light', - dark: 'github-dark', - }, - }, - themeConfig: { - logo: '/logo.svg', - - editLink: { - pattern: 'https://github.com/vitest-dev/vitest/edit/main/docs/:path', - text: 'Suggest changes to this page', - }, - - search: { - provider: 'local', - /* provider: 'algolia', - options: { - appId: 'ZTF29HGJ69', - apiKey: '9c3ced6fed60d2670bb36ab7e8bed8bc', - indexName: 'vitest', - // searchParameters: { - // facetFilters: ['tags:en'], - // }, - }, */ - }, - - socialLinks: [ - { icon: 'mastodon', link: mastodon }, - { icon: 'twitter', link: twitter }, - { icon: 'discord', link: discord }, - { icon: 'github', link: github }, ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ], lastUpdated: true, markdown: { diff --git a/.vitepress/style/vars.css b/.vitepress/style/vars.css index adad72a9..7030fd42 100644 --- a/.vitepress/style/vars.css +++ b/.vitepress/style/vars.css @@ -2,32 +2,12 @@ * Colors * -------------------------------------------------------------------------- */ -<<<<<<< HEAD - :root { - --vp-c-accent: #dab40b; - --vp-c-brand: #6da13f; - --vp-c-brand-1: var(--vp-c-brand-dark); - --vp-c-brand-2: var(--vp-c-brand-darker); - --vp-c-brand-light: #7ec242; - --vp-c-brand-lighter: #93d31c; - --vp-c-brand-dark: #668d11; - --vp-c-brand-darker: #52730d; - --vp-c-text-code: #5d6f5d; - --vp-code-block-bg: rgba(125,125,125,0.04); - --vp-c-text-light-2: rgba(56 56 56 / 70%); - /* fix contrast: lang name on gray code block */ - --vp-c-text-dark-3: rgba(180, 180, 180, 0.7); - --vp-code-copy-code-bg: rgba(125,125,125,0.1); - --vp-code-copy-code-hover-bg: rgba(125,125,125,0.2); - --vp-c-disabled-bg: rgba(125,125,125,0.2); -======= :root { --vp-c-brand-1: #52730d; --vp-c-brand-2: #57791b; --vp-c-brand-3: #506e10; --vp-c-sponsor: #ca2971; --vitest-c-sponsor-hover: #c13071; ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 } .dark { @@ -38,7 +18,6 @@ --vitest-c-sponsor-hover: #e51370; } - /** * Component: Custom Block * -------------------------------------------------------------------------- */ @@ -46,7 +25,7 @@ --vp-custom-block-tip-code-bg: var(--vp-c-brand-soft); --vp-custom-block-danger-code-bg: #a79fa029; --vitest-custom-block-tip-code-text: #4a680c; - --vitest-custom-block-info-code-text: #394f0c + --vitest-custom-block-info-code-text: #394f0c; } .dark { @@ -67,7 +46,7 @@ * Component: Home * -------------------------------------------------------------------------- */ - :root { +:root { --vp-home-hero-name-color: transparent; --vp-home-hero-name-background: -webkit-linear-gradient( 120deg, @@ -94,7 +73,6 @@ } } - /** * Component: Algolia * -------------------------------------------------------------------------- */ diff --git a/api/expect.md b/api/expect.md index e4866718..8c4c66b4 100644 --- a/api/expect.md +++ b/api/expect.md @@ -1,20 +1,14 @@ # expect -下面的类型在下面的类型签名中使用。 +The following types are used in the type signatures below ```ts type Awaitable = T | PromiseLike ``` -<<<<<<< HEAD -`expect` 用于创建断言。在这个上下文中,“断言”是可以调用的函数,用于断言一个语句。Vitest 默认提供 `chai` 断言,并且还提供了基于 `chai` 构建的 `Jest` 兼容断言。 - -例如,这段代码断言一个 `input` 值等于 `2`。如果不是,断言将抛出一个错误,测试将失败。 -======= `expect` is used to create assertions. In this context `assertions` are functions that can be called to assert a statement. Vitest provides `chai` assertions by default and also `Jest` compatible assertions build on top of `chai`. For example, this code asserts that an `input` value is equal to `2`. If it's not, the assertion will throw an error, and the test will fail. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect } from 'vitest' @@ -25,25 +19,19 @@ expect(input).to.equal(2) // chai API expect(input).toBe(2) // jest API ``` -<<<<<<< HEAD -从技术上讲,这个例子没有使用 [`test`](/api/#test) 函数,因此在控制台中,你将看到 Nodejs 错误而不是 Vitest 输出。要了解有关 `test` 的更多信息,请阅读 [测试 API 参考](/api/)。 - -此外,`expect` 还可以静态地使用,以访问后面描述的匹配器函数等更多功能。 -======= Technically this example doesn't use [`test`](/api/#test) function, so in the console you will see Nodejs error instead of Vitest output. To learn more about `test`, please read [Test API Reference](/api/). Also, `expect` can be used statically to access matchers functions, described later, and more. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ::: warning -如果表达式没有类型错误,`expect` 对测试类型没有影响。如果你想将 Vitest 用作 [类型检查器](/guide/testing-types),请使用 [`expectTypeOf`](/api/expect-typeof) 或 [`assertType`](/api/assert-type)。 +`expect` has no effect on testing types, if the expression doesn't have a type error. If you want to use Vitest as [type checker](/guide/testing-types), use [`expectTypeOf`](/api/expect-typeof) or [`assertType`](/api/assert-type). ::: ## soft -- **类型:** `ExpectStatic & (actual: any) => Assertions` +- **Type:** `ExpectStatic & (actual: any) => Assertions` -`expect.soft` 的功能与 `expect` 类似,但它不会在断言失败时终止测试执行,而是继续运行并将失败标记为测试失败。 测试过程中遇到的所有错误都会显示出来,直到测试完成。 +`expect.soft` functions similarly to `expect`, but instead of terminating the test execution upon a failed assertion, it continues running and marks the failure as a test failure. All errors encountered during the test will be displayed until the test is completed. ```ts import { expect, test } from 'vitest' @@ -55,11 +43,7 @@ test('expect.soft test', () => { // At the end of the test, the above errors will be output. ``` -<<<<<<< HEAD -它也可以与 `expect` 一起使用。 如果 `expect` 断言失败,测试将终止并显示所有错误。 -======= It can also be used with `expect`. if `expect` assertion fails, the test will be terminated and all errors will be displayed. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test } from 'vitest' @@ -72,16 +56,12 @@ test('expect.soft test', () => { ``` ::: warning -`expect.soft` 只能在 [`test`](/api/#test) 函数内部使用。 +`expect.soft` can only be used inside the [`test`](/api/#test) function. ::: ## not -<<<<<<< HEAD -使用 `not` 将否定断言。例如,这段代码断言一个 `input` 值不等于 `2`。如果相等,断言将抛出一个错误,测试将失败。 -======= Using `not` will negate the assertion. For example, this code asserts that an `input` value is not equal to `2`. If it's equal, the assertion will throw an error, and the test will fail. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test } from 'vitest' @@ -94,35 +74,8 @@ expect(input).not.toBe(2) // jest API ## toBe -- **类型:** `(value: any) => Awaitable` - -<<<<<<< HEAD - `toBe` 可以用于断言原始类型是否相等,或者对象是否共享相同的引用。它相当于调用 `expect(Object.is(3, 3)).toBe(true)`。如果对象不同,但你想检查它们的结构是否相同,可以使用 [`toEqual`](#toequal)。 - - 例如,下面的代码检查交易员是否有 13 个苹果。 - - ```ts - import { expect, test } from 'vitest' - - const stock = { - type: 'apples', - count: 13, - } - - test('stock has 13 apples', () => { - expect(stock.type).toBe('apples') - expect(stock.count).toBe(13) - }) - - test('stocks are the same', () => { - const refStock = stock // same reference - - expect(stock).toBe(refStock) - }) - ``` +- **Type:** `(value: any) => Awaitable` - 请尽量不要使用 `toBe` 来比较浮点数。由于 JavaScript 对它们进行四舍五入,因此 `0.1 + 0.2` 并不严格等于 `0.3`。要可靠地断言浮点数,请使用 [`toBeCloseTo`](#tobecloseto) 断言。 -======= `toBe` can be used to assert if primitives are equal or that objects share the same reference. It is equivalent of calling `expect(Object.is(3, 3)).toBe(true)`. If the objects are not the same, but you want to check if their structures are identical, you can use [`toEqual`](#toequal). For example, the code below checks if the trader has 13 apples. @@ -148,30 +101,11 @@ test('stocks are the same', () => { ``` Try not to use `toBe` with floating-point numbers. Since JavaScript rounds them, `0.1 + 0.2` is not strictly `0.3`. To reliably assert floating-point numbers, use [`toBeCloseTo`](#tobecloseto) assertion. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeCloseTo -- **类型:** `(value: number, numDigits?: number) => Awaitable` - -<<<<<<< HEAD - 使用 `toBeCloseTo` 来比较浮点数。可选的 `numDigits` 参数限制在小数点后检查的数字位数。例如: +- **Type:** `(value: number, numDigits?: number) => Awaitable` - ```ts - import { expect, test } from 'vitest' - - test.fails('decimals are not equal in javascript', () => { - expect(0.2 + 0.1).toBe(0.3) // 0.2 + 0.1 is 0.30000000000000004 - }) - - test('decimals are rounded to 5 after the point', () => { - // 0.2 + 0.1 is 0.30000 | "000000000004" removed - expect(0.2 + 0.1).toBeCloseTo(0.3, 5) - // nothing from 0.30000000000000004 is removed - expect(0.2 + 0.1).not.toBeCloseTo(0.3, 50) - }) - ``` -======= Use `toBeCloseTo` to compare floating-point numbers. The optional `numDigits` argument limits the number of digits to check _after_ the decimal point. For example: ```ts @@ -188,22 +122,11 @@ test('decimals are rounded to 5 after the point', () => { expect(0.2 + 0.1).not.toBeCloseTo(0.3, 50) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeDefined -- **类型:** `() => Awaitable` - -<<<<<<< HEAD - `toBeDefined` 断言该值不等于 `undefined`。一个有用的用例是检查函数是否 _返回_ 了任何值。 +- **Type:** `() => Awaitable` - ```ts - import { expect, test } from 'vitest' - - function getApples() { - return 3 - } -======= `toBeDefined` asserts that the value is not equal to `undefined`. Useful use case would be to check if function _returned_ anything. ```ts @@ -212,7 +135,6 @@ import { expect, test } from 'vitest' function getApples() { return 3 } ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 test('function returned something', () => { expect(getApples()).toBeDefined() @@ -221,19 +143,8 @@ test('function returned something', () => { ## toBeUndefined -- **类型:** `() => Awaitable` - -<<<<<<< HEAD - 与 `toBeDefined` 相反,`toBeUndefined` 断言该值 _等于_ `undefined`。一个有用的用例是检查函数是否没有 _返回_ 任何值。 +- **Type:** `() => Awaitable` - ```ts - import { expect, test } from 'vitest' - - function getApplesFromStock(stock) { - if (stock === 'Bill') - return 13 - } -======= Opposite of `toBeDefined`, `toBeUndefined` asserts that the value _is_ equal to `undefined`. Useful use case would be to check if function hasn't _returned_ anything. ```ts @@ -243,7 +154,6 @@ function getApplesFromStock(stock) { if (stock === 'Bill') return 13 } ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 test('mary doesn\'t have a stock', () => { expect(getApplesFromStock('Mary')).toBeUndefined() @@ -252,17 +162,8 @@ test('mary doesn\'t have a stock', () => { ## toBeTruthy -- **类型:** `() => Awaitable` +- **Type:** `() => Awaitable` -<<<<<<< HEAD - `toBeTruthy` 断言该值在转换为布尔值时为 true。如果你不关心该值,但只想知道它可以转换为 `true`,则此断言非常有用。 - - 例如,有了这段代码,你不关心 `stocks.getInfo` 的返回值 - 它可能是一个复杂的对象、一个字符串或其他任何东西。代码仍将正常工作。 - - ```ts - import { Stocks } from './stocks.js' - const stocks = new Stocks() -======= `toBeTruthy` asserts that the value is true when converted to boolean. Useful if you don't care for the value, but just want to know it can be converted to `true`. For example, having this code you don't care for the return value of `stocks.getInfo` - it maybe a complex object, a string, or anything else. The code will still work. @@ -285,65 +186,17 @@ import { Stocks } from './stocks.js' const stocks = new Stocks() test('if we know Bill stock, sell apples to him', () => { ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 stocks.sync('Bill') expect(stocks.getInfo('Bill')).toBeTruthy() }) ``` -<<<<<<< HEAD - 因此,如果你想测试 `stocks.getInfo` 是否为真值,你可以编写: - - ```ts - import { expect, test } from 'vitest' - import { Stocks } from './stocks.js' - const stocks = new Stocks() - - test('if we know Bill stock, sell apples to him', () => { - stocks.sync('Bill') - expect(stocks.getInfo('Bill')).toBeTruthy() - }) - ``` - - 在 JavaScript 中,除了 `false`、`null`、`undefined`、`NaN`、`0`、`-0`、`0n`、`""` 和 `document.all` 之外,所有值都是真值。 -======= Everything in JavaScript is truthy, except `false`, `null`, `undefined`, `NaN`, `0`, `-0`, `0n`, `""` and `document.all`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeFalsy -- **类型:** `() => Awaitable` - -<<<<<<< HEAD - `toBeFalsy` 断言该值在转换为布尔值时为 false。如果你不关心该值,但只想知道它是否可以转换为 `false`,则此断言非常有用。 - - 例如,有了这段代码,你不关心 `stocks.stockFailed` 的返回值 - 它可能返回任何假值,但代码仍将正常工作。 - - ```ts - import { Stocks } from './stocks.js' - - const stocks = new Stocks() - stocks.sync('Bill') - if (!stocks.stockFailed('Bill')) - stocks.sell('apples', 'Bill') - ``` - - 因此,如果你想测试 `stocks.stockFailed` 是否为假值,你可以编写: - - ```ts - import { expect, test } from 'vitest' - import { Stocks } from './stocks.js' - - const stocks = new Stocks() - - test('if Bill stock hasn\'t failed, sell apples to him', () => { - stocks.syncStocks('Bill') - expect(stocks.stockFailed('Bill')).toBeFalsy() - }) - ``` +- **Type:** `() => Awaitable` -在 JavaScript 中,除了 `false`、`null`、`undefined`、`NaN`、`0`、`-0`、`0n`、`""` 和 `document.all` 之外,所有值都是真值。 -======= `toBeFalsy` asserts that the value is false when converted to boolean. Useful if you don't care for the value, but just want to know if it can be converted to `false`. For example, having this code you don't care for the return value of `stocks.stockFailed` - it may return any falsy value, but the code will still work. @@ -372,22 +225,11 @@ test('if Bill stock hasn\'t failed, sell apples to him', () => { ``` Everything in JavaScript is truthy, except `false`, `null`, `undefined`, `NaN`, `0`, `-0`, `0n`, `""` and `document.all`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeNull -- **类型:** `() => Awaitable` +- **Type:** `() => Awaitable` -<<<<<<< HEAD - `toBeNull` 简单地断言某个值是否为 `null`。是 `.toBe(null)` 的别名。 - - ```ts - import { expect, test } from 'vitest' - - function apples() { - return null - } -======= `toBeNull` simply asserts if something is `null`. Alias for `.toBe(null)`. ```ts @@ -396,7 +238,6 @@ import { expect, test } from 'vitest' function apples() { return null } ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 test('we don\'t have apples', () => { expect(apples()).toBeNull() @@ -405,21 +246,8 @@ test('we don\'t have apples', () => { ## toBeNaN -- **类型:** `() => Awaitable` - -<<<<<<< HEAD - `toBeNaN` 简单地断言某个值是否为 `NaN`。是 `.toBe(NaN)` 的别名。 +- **Type:** `() => Awaitable` - ```ts - import { expect, test } from 'vitest' - - let i = 0 - - function getApplesCount() { - i++ - return i > 1 ? Number.NaN : i - } -======= `toBeNaN` simply asserts if something is `NaN`. Alias for `.toBe(NaN)`. ```ts @@ -431,7 +259,6 @@ function getApplesCount() { i++ return i > 1 ? Number.NaN : i } ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 test('getApplesCount has some unusual side effects...', () => { expect(getApplesCount()).not.toBeNaN() @@ -441,21 +268,8 @@ test('getApplesCount has some unusual side effects...', () => { ## toBeTypeOf -- **类型:** `(c: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => Awaitable` - -<<<<<<< HEAD - `toBeTypeOf` 断言实际值是否为接收到的类型。 +- **Type:** `(c: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => Awaitable` - ```ts - import { expect, test } from 'vitest' - - const actual = 'stock' - - test('stock is type of string', () => { - expect(actual).toBeTypeOf('string') - }) - ``` -======= `toBeTypeOf` asserts if an actual value is of type of received type. ```ts @@ -467,26 +281,11 @@ test('stock is type of string', () => { expect(actual).toBeTypeOf('string') }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeInstanceOf -- **类型:** `(c: any) => Awaitable` +- **Type:** `(c: any) => Awaitable` -<<<<<<< HEAD - `toBeInstanceOf` 断言实际值是否为接收到的类的实例。 - - ```ts - import { expect, test } from 'vitest' - import { Stocks } from './stocks.js' - - const stocks = new Stocks() - - test('stocks are instance of Stocks', () => { - expect(stocks).toBeInstanceOf(Stocks) - }) - ``` -======= `toBeInstanceOf` asserts if an actual value is instance of received class. ```ts @@ -499,24 +298,11 @@ test('stocks are instance of Stocks', () => { expect(stocks).toBeInstanceOf(Stocks) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeGreaterThan -- **类型:** `(n: number | bigint) => Awaitable` - -<<<<<<< HEAD - `toBeGreaterThan` 断言实际值是否大于接收到的值。相等的值将导致测试失败。 +- **Type:** `(n: number | bigint) => Awaitable` - ```ts - import { expect, test } from 'vitest' - import { getApples } from './stocks.js' - - test('have more then 10 apples', () => { - expect(getApples()).toBeGreaterThan(10) - }) - ``` -======= `toBeGreaterThan` asserts if actual value is greater than received one. Equal values will fail the test. ```ts @@ -527,24 +313,11 @@ test('have more then 10 apples', () => { expect(getApples()).toBeGreaterThan(10) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeGreaterThanOrEqual -- **类型:** `(n: number | bigint) => Awaitable` - -<<<<<<< HEAD - `toBeGreaterThanOrEqual` 断言实际值是否大于或等于接收到的值。 +- **Type:** `(n: number | bigint) => Awaitable` - ```ts - import { expect, test } from 'vitest' - import { getApples } from './stocks.js' - - test('have 11 apples or more', () => { - expect(getApples()).toBeGreaterThanOrEqual(11) - }) - ``` -======= `toBeGreaterThanOrEqual` asserts if actual value is greater than received one or equal to it. ```ts @@ -555,24 +328,11 @@ test('have 11 apples or more', () => { expect(getApples()).toBeGreaterThanOrEqual(11) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeLessThan -- **类型:** `(n: number | bigint) => Awaitable` +- **Type:** `(n: number | bigint) => Awaitable` -<<<<<<< HEAD - `toBeLessThan` 断言实际值是否小于接收到的值。相等的值将导致测试失败。 - - ```ts - import { expect, test } from 'vitest' - import { getApples } from './stocks.js' - - test('have less then 20 apples', () => { - expect(getApples()).toBeLessThan(20) - }) - ``` -======= `toBeLessThan` asserts if actual value is less than received one. Equal values will fail the test. ```ts @@ -583,24 +343,11 @@ test('have less then 20 apples', () => { expect(getApples()).toBeLessThan(20) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toBeLessThanOrEqual -- **类型:** `(n: number | bigint) => Awaitable` - -<<<<<<< HEAD - `toBeLessThanOrEqual` 断言实际值是否小于或等于接收到的值。 +- **Type:** `(n: number | bigint) => Awaitable` - ```ts - import { expect, test } from 'vitest' - import { getApples } from './stocks.js' - - test('have 11 apples or less', () => { - expect(getApples()).toBeLessThanOrEqual(11) - }) - ``` -======= `toBeLessThanOrEqual` asserts if actual value is less than received one or equal to it. ```ts @@ -611,41 +358,11 @@ test('have 11 apples or less', () => { expect(getApples()).toBeLessThanOrEqual(11) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toEqual -- **类型:** `(received: any) => Awaitable` - -<<<<<<< HEAD - `toEqual` 断言实际值是否等于接收到的值或具有相同的结构(如果是对象,则递归比较它们)。你可以在此示例中看到 `toEqual` 和 [`toBe`](#tobe) 之间的区别: - - ```ts - import { expect, test } from 'vitest' - - const stockBill = { - type: 'apples', - count: 13, - } - - const stockMary = { - type: 'apples', - count: 13, - } - - test('stocks have the same properties', () => { - expect(stockBill).toEqual(stockMary) - }) - - test('stocks are not the same', () => { - expect(stockBill).not.toBe(stockMary) - }) - ``` +- **Type:** `(received: any) => Awaitable` - :::warning - 对于 `Error` 对象,不会执行 _深度相等性_。要测试是否抛出了某些内容,请使用 [`toThrowError`](#tothrowerror) 断言。 - ::: -======= `toEqual` asserts if actual value is equal to received one or has the same structure, if it is an object (compares them recursively). You can see the difference between `toEqual` and [`toBe`](#tobe) in this example: ```ts @@ -673,36 +390,18 @@ test('stocks are not the same', () => { :::warning A _deep equality_ will not be performed for `Error` objects. To test if something was thrown, use [`toThrowError`](#tothrowerror) assertion. ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toStrictEqual -- **类型:** `(received: any) => Awaitable` - -<<<<<<< HEAD - `toStrictEqual` 断言实际值是否等于接收到的值或具有相同的结构(如果是对象,则递归比较它们),并且类型相同。 - - 与 [`.toEqual`](#toequal) 的区别: +- **Type:** `(received: any) => Awaitable` - - 检查具有 `undefined` 属性的键。例如,使用 `.toStrictEqual` 时,`{a: undefined, b: 2}` 不匹配 `{b: 2}`。 - - 检查数组的稀疏性。例如,使用 `.toStrictEqual` 时,`[, 1]` 不匹配 `[undefined, 1]`。 - - 检查对象类型是否相等。例如,具有字段 `a` 和 `b` 的类实例将不等于具有字段 `a` 和 `b` 的字面对象。 - - ```ts - import { expect, test } from 'vitest' - - class Stock { - constructor(type) { - this.type = type - } -======= `toStrictEqual` asserts if the actual value is equal to the received one or has the same structure if it is an object (compares them recursively), and of the same type. Differences from [`.toEqual`](#toequal): -- Keys with `undefined` properties are checked. e.g. `{a: undefined, b: 2}` does not match `{b: 2}` when using `.toStrictEqual`. -- Array sparseness is checked. e.g. `[, 1]` does not match `[undefined, 1]` when using `.toStrictEqual`. -- Object types are checked to be equal. e.g. A class instance with fields `a` and` b` will not equal a literal object with fields `a` and `b`. +- Keys with `undefined` properties are checked. e.g. `{a: undefined, b: 2}` does not match `{b: 2}` when using `.toStrictEqual`. +- Array sparseness is checked. e.g. `[, 1]` does not match `[undefined, 1]` when using `.toStrictEqual`. +- Object types are checked to be equal. e.g. A class instance with fields `a` and` b` will not equal a literal object with fields `a` and `b`. ```ts import { expect, test } from 'vitest' @@ -710,7 +409,6 @@ import { expect, test } from 'vitest' class Stock { constructor(type) { this.type = type ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 } } @@ -722,20 +420,8 @@ test('structurally the same, but semantically different', () => { ## toContain -- **类型:** `(received: string) => Awaitable` - -<<<<<<< HEAD - `toContain` 断言实际值是否在数组中。`toContain` 还可以检查一个字符串是否是另一个字符串的子字符串。 +- **Type:** `(received: string) => Awaitable` - ```ts - import { expect, test } from 'vitest' - import { getAllFruits } from './stocks.js' - - test('the fruit list contains orange', () => { - expect(getAllFruits()).toContain('orange') - }) - ``` -======= `toContain` asserts if the actual value is in an array. `toContain` can also check whether a string is a substring of another string. ```ts @@ -746,24 +432,11 @@ test('the fruit list contains orange', () => { expect(getAllFruits()).toContain('orange') }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toContainEqual -- **类型:** `(received: any) => Awaitable` - -<<<<<<< HEAD - `toContainEqual` 断言是否包含具有特定结构和值的项在数组中。它在每个元素内部像 [`toEqual`](#toequal) 一样工作。 +- **Type:** `(received: any) => Awaitable` - ```ts - import { expect, test } from 'vitest' - import { getFruitStock } from './stocks.js' - - test('apple available', () => { - expect(getFruitStock()).toContainEqual({ fruit: 'apple', count: 5 }) - }) - ``` -======= `toContainEqual` asserts if an item with a specific structure and values is contained in an array. It works like [`toEqual`](#toequal) inside for each element. @@ -775,27 +448,11 @@ test('apple available', () => { expect(getFruitStock()).toContainEqual({ fruit: 'apple', count: 5 }) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toHaveLength -- **类型:** `(received: number) => Awaitable` +- **Type:** `(received: number) => Awaitable` -<<<<<<< HEAD - `toHaveLength` 断言对象是否具有 `.length` 属性,并且该属性设置为特定的数字值。 - - ```ts - import { expect, test } from 'vitest' - - test('toHaveLength', () => { - expect('abc').toHaveLength(3) - expect([1, 2, 3]).toHaveLength(3) - - expect('').not.toHaveLength(3) // doesn't have .length of 3 - expect({ length: 3 }).toHaveLength(3) - }) - ``` -======= `toHaveLength` asserts if an object has a `.length` property and it is set to a certain numeric value. ```ts @@ -809,65 +466,11 @@ test('toHaveLength', () => { expect({ length: 3 }).toHaveLength(3) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toHaveProperty -- **类型:** `(key: any, received?: any) => Awaitable` - -<<<<<<< HEAD - `toHaveProperty` 断言对象是否存在提供的引用 `key` 的属性。 +- **Type:** `(key: any, received?: any) => Awaitable` - 你可以提供一个可选的值参数,也称为深度相等性,例如 `toEqual` 匹配器,以比较接收到的属性值。 - - ```ts - import { expect, test } from 'vitest' - - const invoice = { - 'isActive': true, - 'P.O': '12345', - 'customer': { - first_name: 'John', - last_name: 'Doe', - location: 'China', - }, - 'total_amount': 5000, - 'items': [ - { - type: 'apples', - quantity: 10, - }, - { - type: 'oranges', - quantity: 5, - }, - ], - } - - test('John Doe Invoice', () => { - expect(invoice).toHaveProperty('isActive') // assert that the key exists - expect(invoice).toHaveProperty('total_amount', 5000) // assert that the key exists and the value is equal - - expect(invoice).not.toHaveProperty('account') // assert that this key does not exist - - // Deep referencing using dot notation - expect(invoice).toHaveProperty('customer.first_name') - expect(invoice).toHaveProperty('customer.last_name', 'Doe') - expect(invoice).not.toHaveProperty('customer.location', 'India') - - // Deep referencing using an array containing the key - expect(invoice).toHaveProperty('items[0].type', 'apples') - expect(invoice).toHaveProperty('items.0.type', 'apples') // dot notation also works - - // Deep referencing using an array containing the keyPath - expect(invoice).toHaveProperty(['items', 0, 'type'], 'apples') - expect(invoice).toHaveProperty(['items', '0', 'type'], 'apples') // string notation also works - - // Wrap your key in an array to avoid the key from being parsed as a deep reference - expect(invoice).toHaveProperty(['P.O'], '12345') - }) - ``` -======= `toHaveProperty` asserts if a property at provided reference `key` exists for an object. You can provide an optional value argument also known as deep equality, like the `toEqual` matcher to compare the received property value. @@ -919,24 +522,11 @@ test('John Doe Invoice', () => { expect(invoice).toHaveProperty(['P.O'], '12345') }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toMatch -- **类型:** `(received: string | regexp) => Awaitable` +- **Type:** `(received: string | regexp) => Awaitable` -<<<<<<< HEAD - `toMatch` 断言字符串是否与正则表达式或字符串匹配。 - - ```ts - import { expect, test } from 'vitest' - - test('top fruits', () => { - expect('top fruits include apple, orange and grape').toMatch(/apple/) - expect('applefruits').toMatch('fruit') // toMatch also accepts a string - }) - ``` -======= `toMatch` asserts if a string matches a regular expression or a string. ```ts @@ -947,65 +537,15 @@ test('top fruits', () => { expect('applefruits').toMatch('fruit') // toMatch also accepts a string }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ::: tip -如果错误消息中的值被截断得太多,你可以在配置文件中增加 [chaiConfig.truncateThreshold](/config/#chaiconfig-truncatethreshold)。 +If the value in the error message is too truncated, you can increase [chaiConfig.truncateThreshold](/config/#chaiconfig-truncatethreshold) in your config file. ::: ## toMatchObject -- **类型:** `(received: object | array) => Awaitable` - -<<<<<<< HEAD - `toMatchObject` 断言对象是否与对象的一部分属性匹配。 +- **Type:** `(received: object | array) => Awaitable` - 你还可以传递一个对象数组。如果你想检查两个数组在元素数量上是否匹配,这非常有用,与 `arrayContaining` 相反,它允许接收到的数组中有额外的元素。 - - ```ts - import { expect, test } from 'vitest' - - const johnInvoice = { - isActive: true, - customer: { - first_name: 'John', - last_name: 'Doe', - location: 'China', - }, - total_amount: 5000, - items: [ - { - type: 'apples', - quantity: 10, - }, - { - type: 'oranges', - quantity: 5, - }, - ], - } - - const johnDetails = { - customer: { - first_name: 'John', - last_name: 'Doe', - location: 'China', - }, - } - - test('invoice has john personal details', () => { - expect(johnInvoice).toMatchObject(johnDetails) - }) - - test('the number of elements must match exactly', () => { - // Assert that an array of object matches - expect([{ foo: 'bar' }, { baz: 1 }]).toMatchObject([ - { foo: 'bar' }, - { baz: 1 }, - ]) - }) - ``` -======= `toMatchObject` asserts if an object matches a subset of the properties of an object. You can also pass an array of objects. This is useful if you want to check that two arrays match in their number of elements, as opposed to `arrayContaining`, which allows for extra elements in the received array. @@ -1053,38 +593,13 @@ test('the number of elements must match exactly', () => { ]) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toThrowError -- **类型:** `(received: any) => Awaitable` - -- **别名:** `toThrow` - -<<<<<<< HEAD - `toThrowError` 断言当调用函数时是否抛出错误。 - - 你可以提供一个可选参数来测试是否抛出了特定的错误: +- **Type:** `(received: any) => Awaitable` - - 正则表达式:错误消息与模式匹配 - - 字符串:错误消息包含子字符串 +- **Alias:** `toThrow` - :::tip - 你必须将代码包装在一个函数中,否则错误将不会被捕获,测试将失败。 - ::: - - 例如,如果我们想测试 `getFruitStock('pineapples')` 是否会抛出错误,我们可以编写: - - ```ts - import { expect, test } from 'vitest' - - function getFruitStock(type) { - if (type === 'pineapples') { - throw new DiabetesError( - 'Pineapples are not good for people with diabetes' - ) - } -======= `toThrowError` asserts if a function throws an error when it is called. You can provide an optional argument to test that a specific error is thrown: @@ -1104,27 +619,10 @@ import { expect, test } from 'vitest' function getFruitStock(type) { if (type === 'pineapples') throw new DiabetesError('Pineapples are not good for people with diabetes') ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 // Do some other stuff } -<<<<<<< HEAD - test('throws on pineapples', () => { - // Test that the error message says "diabetes" somewhere: these are equivalent - expect(() => getFruitStock('pineapples')).toThrowError(/diabetes/) - expect(() => getFruitStock('pineapples')).toThrowError('diabetes') - - // Test the exact error message - expect(() => getFruitStock('pineapples')).toThrowError( - /^Pineapples are not good for people with diabetes$/ - ) - }) - ``` - - :::tip - 要测试异步函数,请与 [rejects](#rejects) 结合使用。 -======= test('throws on pineapples', () => { // Test that the error message says "diabetes" somewhere: these are equivalent expect(() => getFruitStock('pineapples')).toThrowError(/diabetes/) @@ -1132,74 +630,36 @@ test('throws on pineapples', () => { // Test the exact error message expect(() => getFruitStock('pineapples')).toThrowError( - /^Pineapples are not good for people with diabetes$/, + /^Pineapples are not good for people with diabetes$/ ) }) ``` :::tip To test async functions, use in combination with [rejects](#rejects). ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```js function getAsyncFruitStock() { return Promise.reject(new Error('empty')) } -<<<<<<< HEAD - test('throws on pineapples', async () => { - await expect(() => getAsyncFruitStock()).rejects.toThrowError('empty') - }) - ``` - - ::: -======= test('throws on pineapples', async () => { await expect(() => getAsyncFruitStock()).rejects.toThrowError('empty') }) ``` + ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toMatchSnapshot -- **类型:** `(shape?: Partial | string, message?: string) => void` - -<<<<<<< HEAD - 这确保了一个值与最近的快照匹配。 - - 你可以提供一个可选的 `hint` 字符串参数,该参数附加到测试名称。尽管 Vitest 总是在快照名称的末尾附加一个数字,但短的描述性提示可能比数字更有用,以区分单个 it 或 test 块中的多个快照。Vitest 按名称对相应的 `.snap` 文件中的快照进行排序。 - - :::tip - 当快照不匹配并导致测试失败时,如果预期不匹配,你可以按 `u` 键更新一次快照。或者,你可以传递 `-u` 或 `--update` CLI 选项,使 Vitest 始终更新测试。 - ::: +- **Type:** `(shape?: Partial | string, message?: string) => void` - ```ts - import { expect, test } from 'vitest' - - test('matches snapshot', () => { - const data = { foo: new Set(['bar', 'snapshot']) } - expect(data).toMatchSnapshot() - }) - ``` - - 如果你只测试对象的形状,并且不需要它完全兼容,你还可以提供一个对象的形状: - - ```ts - import { expect, test } from 'vitest' - - test('matches snapshot', () => { - const data = { foo: new Set(['bar', 'snapshot']) } - expect(data).toMatchSnapshot({ foo: expect.any(Set) }) - }) - ``` -======= This ensures that a value matches the most recent snapshot. You can provide an optional `hint` string argument that is appended to the test name. Although Vitest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it or test block. Vitest sorts snapshots by name in the corresponding `.snap` file. :::tip - When snapshot mismatch and causing the test failing, if the mismatch is expected, you can press `u` key to update the snapshot for once. Or you can pass `-u` or `--update` CLI options to make Vitest always update the tests. +When snapshot mismatch and causing the test failing, if the mismatch is expected, you can press `u` key to update the snapshot for once. Or you can pass `-u` or `--update` CLI options to make Vitest always update the tests. ::: ```ts @@ -1221,48 +681,11 @@ test('matches snapshot', () => { expect(data).toMatchSnapshot({ foo: expect.any(Set) }) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toMatchInlineSnapshot -- **类型:** `(shape?: Partial | string, snapshot?: string, message?: string) => void` - -<<<<<<< HEAD - 这确保了一个值与最近的快照匹配。 - - Vitest 将内联快照字符串参数添加到测试文件中的匹配器中(而不是外部的 `.snap` 文件),并更新它。 +- **Type:** `(shape?: Partial | string, snapshot?: string, message?: string) => void` - ```ts - import { expect, test } from 'vitest' - - test('matches inline snapshot', () => { - const data = { foo: new Set(['bar', 'snapshot']) } - // Vitest will update following content when updating the snapshot - expect(data).toMatchInlineSnapshot(` - { - "foo": Set { - "bar", - "snapshot", - }, - } - `) - }) - ``` - - 如果你只测试对象的形状,并且不需要它 100% 兼容,你还可以提供一个对象的形状: - - ```ts - import { expect, test } from 'vitest' - - test('matches snapshot', () => { - const data = { foo: new Set(['bar', 'snapshot']) } - expect(data).toMatchInlineSnapshot( - { foo: expect.any(Set) }, - ` - { - "foo": Any, - } -======= This ensures that a value matches the most recent snapshot. Vitest adds and updates the inlineSnapshot string argument to the matcher in the test file (instead of an external `.snap` file). @@ -1293,7 +716,6 @@ test('matches snapshot', () => { const data = { foo: new Set(['bar', 'snapshot']) } expect(data).toMatchInlineSnapshot( { foo: expect.any(Set) }, ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ` { "foo": Any, @@ -1305,23 +727,9 @@ test('matches snapshot', () => { ## toMatchFileSnapshot -- **类型:** `(filepath: string, message?: string) => Promise` -- **版本:** Since Vitest 0.30.0 - -<<<<<<< HEAD - 与指定的文件内容显式比较或更新快照(而不是 `.snap` 文件)。 +- **Type:** `(filepath: string, message?: string) => Promise` +- **Version:** Since Vitest 0.30.0 - ```ts - import { expect, it } from 'vitest' - - it('render basic', async () => { - const result = renderHTML(h('div', { class: 'foo' })) - await expect(result).toMatchFileSnapshot('./test/basic.output.html') - }) - ``` - - 请注意,由于文件系统操作是异步的,你需要在 `toMatchFileSnapshot()` 中使用 `await`。 -======= Compare or update the snapshot with the content of a file explicitly specified (instead of the `.snap` file). ```ts @@ -1334,65 +742,23 @@ it('render basic', async () => { ``` Note that since file system operation is async, you need to use `await` with `toMatchFileSnapshot()`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toThrowErrorMatchingSnapshot -- **类型:** `(message?: string) => void` - -<<<<<<< HEAD - 与 [`toMatchSnapshot`](#tomatchsnapshot) 相同,但期望与 [`toThrowError`](#tothrowerror) 相同的值。 +- **Type:** `(message?: string) => void` - 如果函数抛出 `Error`,则快照将是错误消息。否则,快照将是函数抛出的值。 -======= The same as [`toMatchSnapshot`](#tomatchsnapshot), but expects the same value as [`toThrowError`](#tothrowerror). ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toThrowErrorMatchingInlineSnapshot -- **类型:** `(snapshot?: string, message?: string) => void` +- **Type:** `(snapshot?: string, message?: string) => void` -<<<<<<< HEAD - 与 [`toMatchInlineSnapshot`](#tomatchinlinesnapshot) 相同,但期望与 [`toThrowError`](#tothrowerror) 相同的值。 - - 如果函数抛出 `Error`,则快照将是错误消息。否则,快照将是函数抛出的值。 -======= The same as [`toMatchInlineSnapshot`](#tomatchinlinesnapshot), but expects the same value as [`toThrowError`](#tothrowerror). ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## toHaveBeenCalled -- **类型:** `() => Awaitable` - -<<<<<<< HEAD - 此断言用于测试函数是否已被调用。需要将 spy 函数传递给 `expect`。 - - ```ts - import { expect, test, vi } from 'vitest' - - const market = { - buy(subject: string, amount: number) { - // ... - }, - } - - test('spy function', () => { - const buySpy = vi.spyOn(market, 'buy') - - expect(buySpy).not.toHaveBeenCalled() - - market.buy('apples', 10) - - expect(buySpy).toHaveBeenCalled() - }) - ``` - -## toHaveBeenCalledTimes - -- **类型**: `(amount: number) => Awaitable` +- **Type:** `() => Awaitable` -此断言检查函数是否被调用了特定次数。需要将 spy 函数传递给 `expect`。 -======= This assertion is useful for testing that a function has been called. Requires a spy function to be passed to `expect`. ```ts @@ -1420,7 +786,6 @@ test('spy function', () => { - **Type**: `(amount: number) => Awaitable` This assertion checks if a function was called a certain amount of times. Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1443,15 +808,9 @@ test('spy function called two times', () => { ## toHaveBeenCalledWith -<<<<<<< HEAD -- **类型**: `(...args: any[]) => Awaitable` - -此断言检查函数是否至少被调用一次,并且使用了特定的参数。需要将 spy 函数传递给 `expect`。 -======= - **Type**: `(...args: any[]) => Awaitable` This assertion checks if a function was called at least once with certain parameters. Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1475,15 +834,9 @@ test('spy function', () => { ## toHaveBeenLastCalledWith -<<<<<<< HEAD -- **类型**: `(...args: any[]) => Awaitable` - -此断言检查函数在最后一次调用时是否使用了特定的参数。需要将 spy 函数传递给 `expect`。 -======= - **Type**: `(...args: any[]) => Awaitable` This assertion checks if a function was called with certain parameters at it's last invocation. Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1507,19 +860,11 @@ test('spy function', () => { ## toHaveBeenNthCalledWith -<<<<<<< HEAD -- **类型**: `(time: number, ...args: any[]) => Awaitable` - -此断言检查函数在特定时间是否使用了特定的参数。计数从 1 开始。因此,要检查第二个条目,你可以编写 `.toHaveBeenNthCalledWith(2, ...)`。需要将 spy 函数传递给 `expect`。 - -需要将 spy 函数传递给 `expect`。 -======= - **Type**: `(time: number, ...args: any[]) => Awaitable` This assertion checks if a function was called with certain parameters at the certain time. The count starts at 1. So, to check the second entry, you would write `.toHaveBeenNthCalledWith(2, ...)`. Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1542,15 +887,9 @@ test('first call of spy function called with right params', () => { ## toHaveReturned -<<<<<<< HEAD -- **类型**: `() => Awaitable` - -更好地了解你的问题。此断言检查函数是否至少成功返回了一次值(即未抛出错误)。需要将 spy 函数传递给 `expect`。 -======= - **Type**: `() => Awaitable` This assertion checks if a function has successfully returned a value at least once (i.e., did not throw an error). Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1572,15 +911,9 @@ test('spy function returned a value', () => { ## toHaveReturnedTimes -<<<<<<< HEAD -- **类型**: `(amount: number) => Awaitable` - -此断言检查函数是否成功返回了确切次数的值(即未抛出错误)。需要将 spy 函数传递给 `expect`。 -======= - **Type**: `(amount: number) => Awaitable` This assertion checks if a function has successfully returned a value exact amount of times (i.e., did not throw an error). Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1597,15 +930,9 @@ test('spy function returns a value two times', () => { ## toHaveReturnedWith -<<<<<<< HEAD -- **类型**: `(returnValue: any) => Awaitable` - -你可以调用此断言来检查函数是否至少成功返回了一次具有特定参数的值。需要将 spy 函数传递给 `expect`。 -======= - **Type**: `(returnValue: any) => Awaitable` You can call this assertion to check if a function has successfully returned a value with certain parameters at least once. Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1621,15 +948,9 @@ test('spy function returns a product', () => { ## toHaveLastReturnedWith -<<<<<<< HEAD -- **类型**: `(returnValue: any) => Awaitable` - -你可以调用此断言来检查函数是否在最后一次调用时成功返回了具有特定参数的值。需要将 spy 函数传递给 `expect`。 -======= - **Type**: `(returnValue: any) => Awaitable` You can call this assertion to check if a function has successfully returned a value with certain parameters on it's last invoking. Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1646,15 +967,9 @@ test('spy function returns bananas on a last call', () => { ## toHaveNthReturnedWith -<<<<<<< HEAD -- **类型**: `(time: number, returnValue: any) => Awaitable` - -你可以调用此断言来检查函数是否在特定调用时成功返回了具有特定参数的值。需要将 spy 函数传递给 `expect`。 -======= - **Type**: `(time: number, returnValue: any) => Awaitable` You can call this assertion to check if a function has successfully returned a value with certain parameters on a certain call. Requires a spy function to be passed to `expect`. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { expect, test, vi } from 'vitest' @@ -1671,15 +986,9 @@ test('spy function returns bananas on second call', () => { ## toSatisfy -<<<<<<< HEAD -- **类型:** `(predicate: (value: any) => boolean) => Awaitable` - -此断言检查一个值是否满足特定的谓词。 -======= - **Type:** `(predicate: (value: any) => boolean) => Awaitable` This assertion checks if a value satisfies a certain predicate. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts describe('toSatisfy()', () => { @@ -1697,22 +1006,8 @@ describe('toSatisfy()', () => { ## resolves -- **类型:** `Promisify` - -<<<<<<< HEAD - `resolves` 旨在在断言异步代码时消除样板代码。使用它来从挂起的 Promise 中解包值,并使用通常的断言来断言其值。如果 Promise 被拒绝,断言将失败。 - - 它返回相同的 `Assertions` 对象,但所有匹配器现在都返回 `Promise`,因此你需要 `await` 它。也适用于 `chai` 断言。 +- **Type:** `Promisify` - 例如,如果你有一个调用 API 并返回一些数据的函数,你可以使用此代码断言其返回值: - - ```ts - import { expect, test } from 'vitest' - - async function buyApples() { - return fetch('/buy/apples').then(r => r.json()) - } -======= `resolves` is intended to remove boilerplate when asserting asynchronous code. Use it to unwrap value from the pending promise and assert its value with usual assertions. If the promise rejects, the assertion will fail. It returns the same `Assertions` object, but all matchers now return `Promise`, so you would need to `await` it. Also works with `chai` assertions. @@ -1725,7 +1020,6 @@ import { expect, test } from 'vitest' async function buyApples() { return fetch('/buy/apples').then(r => r.json()) } ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 test('buyApples returns new stock id', async () => { // toEqual returns a promise now, so you HAVE to await it @@ -1734,35 +1028,14 @@ test('buyApples returns new stock id', async () => { }) ``` -<<<<<<< HEAD - :::warning - 如果未等待断言,则你将拥有一个虚假的测试,每次都会通过。为确保实际调用了断言,你可以使用 [`expect.assertions(number)`](#expect-assertions)。 - ::: -======= :::warning If the assertion is not awaited, then you will have a false-positive test that will pass every time. To make sure that assertions are actually called, you may use [`expect.assertions(number)`](#expect-assertions). ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## rejects -- **类型:** `Promisify` - -<<<<<<< HEAD - `rejects` 旨在在断言异步代码时消除样板代码。使用它来解包 Promise 被拒绝的原因,并使用通常的断言来断言其值。如果 Promise 成功解析,则断言将失败。 +- **Type:** `Promisify` - 它返回相同的 `Assertions` 对象,但所有匹配器现在都返回 `Promise`,因此你需要 `await` 它。也适用于 `chai` 断言。 - - 例如,如果你有一个在调用时失败的函数,你可以使用以下代码来断言原因: - - ```ts - import { expect, test } from 'vitest' - - async function buyApples(id) { - if (!id) - throw new Error('no id') - } -======= `rejects` is intended to remove boilerplate when asserting asynchronous code. Use it to unwrap reason why the promise was rejected, and assert its value with usual assertions. If the promise successfully resolves, the assertion will fail. It returns the same `Assertions` object, but all matchers now return `Promise`, so you would need to `await` it. Also works with `chai` assertions. @@ -1776,7 +1049,6 @@ async function buyApples(id) { if (!id) throw new Error('no id') } ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 test('buyApples throws an error when no id provided', async () => { // toThrow returns a promise now, so you HAVE to await it @@ -1784,49 +1056,14 @@ test('buyApples throws an error when no id provided', async () => { }) ``` -<<<<<<< HEAD - :::warning - 如果未等待断言,则你将拥有一个虚假的测试,每次都会通过。为确保实际调用了断言,你可以使用 [`expect.assertions(number)`](#expect-assertions)。 - ::: -======= :::warning If the assertion is not awaited, then you will have a false-positive test that will pass every time. To make sure that assertions were actually called, you can use [`expect.assertions(number)`](#expect-assertions). ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.assertions -- **类型:** `(count: number) => void` - -<<<<<<< HEAD - 在测试通过或失败后,验证测试期间调用了特定数量的断言。一个有用的情况是检查异步代码是否被调用。 - - 例如,如果我们有一个异步调用两个匹配器的函数,我们可以断言它们实际上被调用了。 - - ```ts - import { expect, test } from 'vitest' - - async function doAsync(...cbs) { - await Promise.all(cbs.map((cb, index) => cb({ index }))) - } - - test('all assertions are called', async () => { - expect.assertions(2) - function callback1(data) { - expect(data).toBeTruthy() - } - function callback2(data) { - expect(data).toBeTruthy() - } - - await doAsync(callback1, callback2) - }) - ``` +- **Type:** `(count: number) => void` - ::: warning - 在使用 `assertions` 进行异步并发测试时,必须使用来自本地 [测试上下文](/guide/test-context) 的 `expect` 来确保检测到正确的测试。 - ::: -======= After the test has passed or failed verify that a certain number of assertions was called during a test. A useful case would be to check if an asynchronous code was called. For example, if we have a function that asynchronously calls two matchers, we can assert that they were actually called. @@ -1835,9 +1072,7 @@ For example, if we have a function that asynchronously calls two matchers, we ca import { expect, test } from 'vitest' async function doAsync(...cbs) { - await Promise.all( - cbs.map((cb, index) => cb({ index })), - ) + await Promise.all(cbs.map((cb, index) => cb({ index }))) } test('all assertions are called', async () => { @@ -1852,46 +1087,15 @@ test('all assertions are called', async () => { await doAsync(callback1, callback2) }) ``` + ::: warning When using `assertions` with async concurrent tests, `expect` from the local [Test Context](/guide/test-context.md) must be used to ensure the right test is detected. ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.hasAssertions -- **类型:** `() => void` - -<<<<<<< HEAD - 在测试通过或失败后,验证测试期间至少调用了一个断言。一个有用的情况是检查异步代码是否被调用。 - - 例如,如果你有一个调用回调函数的代码,我们可以在回调函数内部进行断言,但是如果我们不检查是否调用了断言,测试将始终通过。 - - ```ts - import { expect, test } from 'vitest' - import { db } from './db.js' - const cbs = [] - - function onSelect(cb) { - cbs.push(cb) - } - - // after selecting from db, we call all callbacks - function select(id) { - return db.select({ id }).then((data) => { - return Promise.all(cbs.map(cb => cb(data))) - }) - } +- **Type:** `() => void` - test('callback was called', async () => { - expect.hasAssertions() - onSelect((data) => { - // should be called on select - expect(data).toBeTruthy() - }) - // if not awaited, test will fail - // if you don't have expect.hasAssertions(), test will pass - await select(3) -======= After the test has passed or failed verify that at least one assertion was called during a test. A useful case would be to check if an asynchronous code was called. For example, if you have a code that calls a callback, we can make an assertion inside a callback, but the test will always pass if we don't check if an assertion was called. @@ -1909,10 +1113,7 @@ function onSelect(cb) { // after selecting from db, we call all callbacks function select(id) { return db.select({ id }).then((data) => { - return Promise.all( - cbs.map(cb => cb(data)), - ) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 + return Promise.all(cbs.map(cb => cb(data))) }) } @@ -1930,20 +1131,8 @@ test('callback was called', async () => { ## expect.unreachable -- **类型:** `(message?: string) => never` +- **Type:** `(message?: string) => never` -<<<<<<< HEAD - 此方法用于断言永远不应该到达一条线。 - - 例如,如果我们想测试 `build()` 由于接收目录没有 `src` 文件夹而抛出,并且还单独处理每个错误,我们可以这样做: - - ```ts - import { expect, test } from 'vitest' - - async function build(dir) { - if (dir.includes('no-src')) - throw new Error(`${dir}/src does not exist`) -======= This method is used to asserting that a line should never be reached. For example, if we want to test that `build()` throws due to receiving directories having no `src` folder, and also handle each error separately, we could do this: @@ -1965,42 +1154,11 @@ test.each(errorDirs)('build fails with "%s"', async (dir) => { try { await build(dir) expect.unreachable('Should not pass build') ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 } catch (err: any) { expect(err).toBeInstanceOf(Error) expect(err.stack).toContain('build') -<<<<<<< HEAD - const errorDirs = [ - 'no-src-folder', - // ... - ] - - test.each(errorDirs)('build fails with "%s"', async (dir) => { - try { - await build(dir) - expect.unreachable('Should not pass build') - } - catch (err: any) { - expect(err).toBeInstanceOf(Error) - expect(err.stack).toContain('build') - - switch (dir) { - case 'no-src-folder': - expect(err.message).toBe(`${dir}/src does not exist`) - break - default: - // to exhaust all error tests - expect.unreachable('All error test must be handled') - break - } - } - }) - ``` - - -======= switch (dir) { case 'no-src-folder': expect(err.message).toBe(`${dir}/src does not exist`) @@ -2013,23 +1171,11 @@ test.each(errorDirs)('build fails with "%s"', async (dir) => { } }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.anything -- **类型:** `() => any` - -<<<<<<< HEAD - 这个不对称的匹配器,当与相等检查一起使用时,将始终返回 `true`。如果你只想确保属性存在,这将非常有用。 +- **Type:** `() => any` - ```ts - import { expect, test } from 'vitest' - - test('object has "apples" key', () => { - expect({ apples: 22 }).toEqual({ apples: expect.anything() }) - }) - ``` -======= This asymmetric matcher, when used with equality check, will always return `true`. Useful, if you just want to be sure that the property exist. ```ts @@ -2039,24 +1185,11 @@ test('object has "apples" key', () => { expect({ apples: 22 }).toEqual({ apples: expect.anything() }) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.any -- **类型:** `(constructor: unknown) => any` - -<<<<<<< HEAD - 这个不对称的匹配器,当与相等检查一起使用时,只有在值是指定构造函数的实例时才会返回 `true`。如果你有一个每次生成的值,并且你只想知道它是否具有适当的类型,这将非常有用。 +- **Type:** `(constructor: unknown) => any` - ```ts - import { expect, test } from 'vitest' - import { generateId } from './generators.js' - - test('"id" is a number', () => { - expect({ id: generateId() }).toEqual({ id: expect.any(Number) }) - }) - ``` -======= This asymmetric matcher, when used with an equality check, will return `true` only if the value is an instance of a specified constructor. Useful, if you have a value that is generated each time, and you only want to know that it exists with a proper type. ```ts @@ -2067,18 +1200,17 @@ test('"id" is a number', () => { expect({ id: generateId() }).toEqual({ id: expect.any(Number) }) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.closeTo -- **类型:** `(expected: any, precision?: number) => any` -- **版本:** Since Vitest 1.0.0 +- **Type:** `(expected: any, precision?: number) => any` +- **Version:** Since Vitest 1.0.0 -当比较对象属性或数组项中的浮点数时,`expect.closeTo`非常有用。但如果你需要比较一个数字,请使用`.toBeCloseTo`。 +`expect.closeTo` is useful when comparing floating point numbers in object properties or array item. If you need to compare a number, please use `.toBeCloseTo` instead. -可选的`numDigits`参数用于限制小数点后要检查的位数。默认值为`2`,即测试条件为`Math.abs(expected - received) < 0.005`(即 10 的负 2 次方除以 2)。 +The optional `numDigits` argument limits the number of digits to check **after** the decimal point. For the default value `2`, the test criterion is `Math.abs(expected - received) < 0.005 (that is, 10 ** -2 / 2)`. -例如,以下测试在精度为 5 位的情况下通过: +For example, this test passes with a precision of 5 digits: ```js test('compare float in object properties', () => { @@ -2094,24 +1226,8 @@ test('compare float in object properties', () => { ## expect.arrayContaining -- **类型:** `(expected: T[]) => any` +- **Type:** `(expected: T[]) => any` -<<<<<<< HEAD - 当与相等检查一起使用时,这个不对称的匹配器将在值是数组并包含指定项时返回 `true`。 - - ```ts - import { expect, test } from 'vitest' - - test('basket includes fuji', () => { - const basket = { - varieties: ['Empire', 'Fuji', 'Gala'], - count: 3, - } - expect(basket).toEqual({ - count: 3, - varieties: expect.arrayContaining(['Fuji']), - }) -======= When used with an equality check, this asymmetric matcher will return `true` if the value is an array and contains specified items. ```ts @@ -2119,54 +1235,24 @@ import { expect, test } from 'vitest' test('basket includes fuji', () => { const basket = { - varieties: [ - 'Empire', - 'Fuji', - 'Gala', - ], - count: 3 + varieties: ['Empire', 'Fuji', 'Gala'], + count: 3, } expect(basket).toEqual({ count: 3, - varieties: expect.arrayContaining(['Fuji']) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 + varieties: expect.arrayContaining(['Fuji']), }) }) ``` -<<<<<<< HEAD - :::tip - 你可以使用 `expect.not` 与此匹配器一起使用,以否定预期值。 - ::: -======= :::tip You can use `expect.not` with this matcher to negate the expected value. ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.objectContaining -- **类型:** `(expected: any) => any` - -<<<<<<< HEAD - 当与相等检查一起使用时,这个不对称的匹配器将在值具有类似形状时返回 `true`。 - - ```ts - import { expect, test } from 'vitest' - - test('basket has empire apples', () => { - const basket = { - varieties: [ - { - name: 'Empire', - count: 1, - }, - ], - } - expect(basket).toEqual({ - varieties: [expect.objectContaining({ name: 'Empire' })], - }) -======= +- **Type:** `(expected: any) => any` + When used with an equality check, this asymmetric matcher will return `true` if the value has a similar shape. ```ts @@ -2178,48 +1264,23 @@ test('basket has empire apples', () => { { name: 'Empire', count: 1, - } + }, ], } expect(basket).toEqual({ - varieties: [ - expect.objectContaining({ name: 'Empire' }), - ] ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 + varieties: [expect.objectContaining({ name: 'Empire' })], }) }) ``` -<<<<<<< HEAD - :::tip - 你可以使用 `expect.not` 与此匹配器一起使用,以否定预期值。 - ::: -======= :::tip You can use `expect.not` with this matcher to negate the expected value. ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.stringContaining -- **类型:** `(expected: any) => any` - -<<<<<<< HEAD - 当与相等检查一起使用时,这个不对称的匹配器将在值是字符串并包含指定子字符串时返回 `true`。 +- **Type:** `(expected: any) => any` - ```ts - import { expect, test } from 'vitest' - - test('variety has "Emp" in its name', () => { - const variety = { - name: 'Empire', - count: 1, - } - expect(variety).toEqual({ - name: expect.stringContaining('Emp'), - count: 1, - }) -======= When used with an equality check, this asymmetric matcher will return `true` if the value is a string and contains a specified substring. ```ts @@ -2233,41 +1294,18 @@ test('variety has "Emp" in its name', () => { expect(variety).toEqual({ name: expect.stringContaining('Emp'), count: 1, ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) }) ``` -<<<<<<< HEAD - :::tip - 你可以使用 `expect.not` 与此匹配器一起使用,以否定预期值。 - ::: -======= :::tip You can use `expect.not` with this matcher to negate the expected value. ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.stringMatching -- **类型:** `(expected: any) => any` +- **Type:** `(expected: any) => any` -<<<<<<< HEAD - 当与相等检查一起使用时,这个不对称的匹配器将在值是字符串并包含指定子字符串或字符串与正则表达式匹配时返回 `true`。 - - ```ts - import { expect, test } from 'vitest' - - test('variety ends with "re"', () => { - const variety = { - name: 'Empire', - count: 1, - } - expect(variety).toEqual({ - name: expect.stringMatching(/re$/), - count: 1, - }) -======= When used with an equality check, this asymmetric matcher will return `true` if the value is a string and contains a specified substring or if the string matches a regular expression. ```ts @@ -2281,34 +1319,18 @@ test('variety ends with "re"', () => { expect(variety).toEqual({ name: expect.stringMatching(/re$/), count: 1, ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) }) ``` -<<<<<<< HEAD - :::tip - 你可以使用 `expect.not` 与此匹配器一起使用,以否定预期值。 - ::: -======= :::tip You can use `expect.not` with this matcher to negate the expected value. ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.addSnapshotSerializer -- **类型:** `(plugin: PrettyFormatPlugin) => void` - -<<<<<<< HEAD - 此方法添加自定义序列化程序,当创建快照时调用这些序列化程序。这是一个高级功能 - 如果你想了解更多信息,请阅读有关自定义序列化程序的指南。 +- **Type:** `(plugin: PrettyFormatPlugin) => void` - 如果你正在添加自定义序列化程序,应在 [`setupFiles`](/config/#setupfiles) 中调用此方法。这将影响到每个快照。 - - :::tip - 如果你之前使用 Vue CLI 和 Jest,你可能想要安装 [jest-serializer-vue](https://www.npmjs.com/package/jest-serializer-vue)。否则,你的快照将被包装在一个字符串中,这会导致 `"` 被转义。 - ::: -======= This method adds custom serializers that are called when creating a snapshot. This is an advanced feature - if you want to know more, please read a [guide on custom serializers](/guide/snapshot#custom-serializer). If you are adding custom serializers, you should call this method inside [`setupFiles`](/config/#setupfiles). This will affect every snapshot. @@ -2316,35 +1338,11 @@ If you are adding custom serializers, you should call this method inside [`setup :::tip If you previously used Vue CLI with Jest, you might want to install [jest-serializer-vue](https://www.npmjs.com/package/jest-serializer-vue). Otherwise, your snapshots will be wrapped in a string, which cases `"` to be escaped. ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ## expect.extend -- **类型:** `(matchers: MatchersObject) => void` - -<<<<<<< HEAD - 你可以使用自己的默认匹配器来扩展默认匹配器。此函数用于使用自定义匹配器扩展匹配器对象。 - - 当你以这种方式定义匹配器时,你还创建了不对称的匹配器,可以像 `expect.stringContaining` 一样使用它们。 +- **Type:** `(matchers: MatchersObject) => void` - ```ts - import { expect, test } from 'vitest' - - test('custom matchers', () => { - expect.extend({ - toBeFoo: (received, expected) => { - if (received !== 'foo') { - return { - message: () => `expected ${received} to be foo`, - pass: false, - } - } - }, - }) - - expect('foo').toBeFoo() - expect({ foo: 'foo' }).toEqual({ foo: expect.toBeFoo() }) -======= You can extend default matchers with your own. This function is used to extend the matchers object with custom matchers. When you define matchers that way, you also create asymmetric matchers that can be used like `expect.stringContaining`. @@ -2362,18 +1360,8 @@ test('custom matchers', () => { } } }, ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) -<<<<<<< HEAD - ::: tip - 如果你希望你的匹配器出现在每个测试中,你应该在 [`setupFiles`](/config/#setupFiles) 中调用此方法。 - ::: - - 此函数与 Jest 的 `expect.extend` 兼容,因此使用它创建自定义匹配器的任何库都可以与 Vitest 一起使用。 - - 如果你使用 TypeScript,自 Vitest 0.31.0 起,你可以使用以下代码在环境声明文件(例如:`vitest.d.ts`)中扩展默认的 `Assertion` 接口: -======= expect('foo').toBeFoo() expect({ foo: 'foo' }).toEqual({ foo: expect.toBeFoo() }) }) @@ -2384,7 +1372,6 @@ If you want your matchers to appear in every test, you should call this method i ::: This function is compatible with Jest's `expect.extend`, so any library that uses it to create custom matchers will work with Vitest. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 If you are using TypeScript, since Vitest 0.31.0 you can extend default `Assertion` interface in an ambient declaration file (e.g: `vitest.d.ts`) with the code below: @@ -2393,15 +1380,6 @@ interface CustomMatchers { toBeFoo(): R } -<<<<<<< HEAD - ::: warning - 不要忘记在你的 `tsconfig.json` 中包含环境声明文件。 - ::: - - :::tip - 如果你想了解更多信息,请查看 [扩展断言](/guide/extending-matchers)。 - ::: -======= declare module 'vitest' { interface Assertion extends CustomMatchers {} interface AsymmetricMatchersContaining extends CustomMatchers {} @@ -2415,4 +1393,3 @@ Don't forget to include the ambient declaration file in your `tsconfig.json`. :::tip If you want to know more, checkout [guide on extending matchers](/guide/extending-matchers). ::: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 diff --git a/api/index.md b/api/index.md index 6b92302e..7120f975 100644 --- a/api/index.md +++ b/api/index.md @@ -2,9 +2,9 @@ outline: deep --- -# API 索引 +# Test API Reference -下面的变量中使用了以下类型签名 +The following types are used in the type signatures below ```ts type Awaitable = T | PromiseLike @@ -12,19 +12,19 @@ type TestFunction = () => Awaitable interface TestOptions { /** - * 如果测试执行时间过长,将会导致测试失败。 + * Will fail the test if it takes too long to execute */ timeout?: number /** - * 如果测试失败,将会重试指定次数。 + * Will retry the test specific number of times if it fails * * @default 0 */ retry?: number /** - * 即使每次测试失败,也会多次重复相同的测试 - * 如果您有 "retry" 选项并且它失败了,它将在每个周期中使用每个重试 - * 用于调试随机失败的情况非常有用 + * Will repeat the same test several times even if it fails each time + * If you have "retry" option and it fails, it will use every retry in each cycle + * Useful for debugging random failings * * @default 0 */ @@ -32,30 +32,17 @@ interface TestOptions { } ``` -当一个测试函数返回一个 promise 时,Vitest 将等待直到它被解决以收集异步的期望值。 如果 promise 被拒绝,测试将失败。 +When a test function returns a promise, the runner will wait until it is resolved to collect async expectations. If the promise is rejected, the test will fail. -::: tip 提示 -在 Jest 中,`TestFunction` 也可以是 `(done: DoneCallback) => void` 类型。 如果使用此选项,则在调用 `done` 之前测试不会结束。 你可以使用 `async` 函数实现相同的目的,请参阅迁移指南中的[回调](../guide/migration#done-callback)部分。 +::: tip +In Jest, `TestFunction` can also be of type `(done: DoneCallback) => void`. If this form is used, the test will not be concluded until `done` is called. You can achieve the same using an `async` function, see the [Migration guide Done Callback section](/guide/migration#done-callback). ::: ## test -- **类型:** `(name: string | Function, fn: TestFunction, timeout?: number | TestOptions) => void` -- **别名:** `it` - -<<<<<<< HEAD - `test` 定义了一组关于测试期望的方法。它接收测试名称和一个含有测试期望的函数。 +- **Type:** `(name: string | Function, fn: TestFunction, timeout?: number | TestOptions) => void` +- **Alias:** `it` - 同时,可以提供一个超时时限(以毫秒为单位)用于指定等待多长时间后终止测试,默认为 5 秒。你也可以通过 [testTimeout](/config/#testtimeout) 选项进行全局配置。 - - ```ts - import { expect, test } from 'vitest' - - test('should work as expected', () => { - expect(Math.sqrt(4)).toBe(2) - }) - ``` -======= `test` defines a set of related expectations. It receives the test name and a function that holds the expectations to test. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before terminating. The default is 5 seconds, and can be configured globally with [testTimeout](/config/#testtimeout) @@ -67,40 +54,13 @@ test('should work as expected', () => { expect(Math.sqrt(4)).toBe(2) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### test.extend -- **类型:** `>(fixtures: Fixtures): TestAPI` -- **别名:** `it.extend` -- **版本:** Vitest 0.32.3 - -<<<<<<< HEAD - 使用 `test.extend` 来扩展带有自定义装置的测试上下文。这将返回一个新的 `test` 并且它也是可扩展的,因此你可以根据需要通过扩展它来组合更多装置或覆盖现有装置。有关详细信息,请参阅[扩展测试上下文](/guide/test-context.html#test-extend)。 - - ```ts - import { expect, test } from 'vitest' - - const todos = [] - const archive = [] - - const myTest = test.extend({ - todos: async ({ task }, use) => { - todos.push(1, 2, 3) - await use(todos) - todos.length = 0 - }, - archive, - }) - - myTest('add item', ({ todos }) => { - expect(todos.length).toBe(3) - - todos.push(4) - expect(todos.length).toBe(4) - }) - ``` -======= +- **Type:** `>(fixtures: Fixtures): TestAPI` +- **Alias:** `it.extend` +- **Version:** Vitest 0.32.3 + Use `test.extend` to extend the test context with custom fixtures. This will return a new `test` and it's also extendable, so you can compose more fixtures or override existing ones by extending it as you need. See [Extend Test Context](/guide/test-context.html#test-extend) for more information. ```ts @@ -115,7 +75,7 @@ const myTest = test.extend({ await use(todos) todos.length = 0 }, - archive + archive, }) myTest('add item', ({ todos }) => { @@ -125,37 +85,12 @@ myTest('add item', ({ todos }) => { expect(todos.length).toBe(4) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### test.skip -- **类型:** `(name: string | Function, fn: TestFunction, timeout?: number | TestOptions) => void` -- **别名:** `it.skip` - -<<<<<<< HEAD - 如果你想跳过运行某些测试,但由于一些原因不想删除代码,你可以使用 `test.skip` 来避免运行它们。 +- **Type:** `(name: string | Function, fn: TestFunction, timeout?: number | TestOptions) => void` +- **Alias:** `it.skip` - ```ts - import { assert, test } from 'vitest' - - test.skip('skipped test', () => { - // 跳过测试,没有错误 - assert.equal(Math.sqrt(4), 3) - }) - ``` - - 你还可以通过在其 [测试上下文](/guide/test-context) 上动态调用 `skip` 来跳过测试: - - ```ts - import { assert, test } from 'vitest' - - test('skipped test', (context) => { - context.skip() - // Test skipped, no error - assert.equal(Math.sqrt(4), 3) - }) - ``` -======= If you want to skip running certain tests, but you don't want to delete the code due to any reason, you can use `test.skip` to avoid running them. ```ts @@ -178,26 +113,12 @@ test('skipped test', (context) => { assert.equal(Math.sqrt(4), 3) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### test.skipIf -- **类型:** `(condition: any) => Test` -- **别名:** `it.skipIf` +- **Type:** `(condition: any) => Test` +- **Alias:** `it.skipIf` -<<<<<<< HEAD - 在某些情况下,你可能会在不同的环境中多次运行测试,并且某些测试可能基于特定环境下运行。只要条件成立,你就可以使用 `test.skipIf` 跳过测试,而不是用 `if` 包裹测试代码。 - - ```ts - import { assert, test } from 'vitest' - - const isDev = process.env.NODE_ENV === 'development' - - test.skipIf(isDev)('prod only test', () => { - // 只在生产环境下进行测试 - }) - ``` -======= In some cases you might run tests multiple times with different environments, and some of the tests might be environment-specific. Instead of wrapping the test code with `if`, you can use `test.skipIf` to skip the test whenever the condition is truthy. ```ts @@ -209,22 +130,17 @@ test.skipIf(isDev)('prod only test', () => { // this test only runs in production }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ::: warning -当 Vitest 作为 [类型检查器](/guide/testing-types) 时,你不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ### test.runIf -- **类型:** `(condition: any) => Test` -- **别名:** `it.runIf` +- **Type:** `(condition: any) => Test` +- **Alias:** `it.runIf` -<<<<<<< HEAD -[test.skipIf](#testskipif) 的相反面。 -======= Opposite of [test.skipIf](#test-skipif). ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts import { assert, test } from 'vitest' @@ -232,45 +148,19 @@ import { assert, test } from 'vitest' const isDev = process.env.NODE_ENV === 'development' test.runIf(isDev)('dev only test', () => { -<<<<<<< HEAD - // 只在开发环境下进行测试 -======= // this test only runs in development ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) ``` ::: warning -当 Vitest 作为 [类型检查器](/guide/testing-types) 时,你不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ### test.only -- **类型:** `(name: string | Function, fn: TestFunction, timeout?: number) => void` -- **别名:** `it.only` +- **Type:** `(name: string | Function, fn: TestFunction, timeout?: number) => void` +- **Alias:** `it.only` -<<<<<<< HEAD - 使用 `test.only` 只允许特定条件的测试套件。这在调试模式下是很有用的。 - - 同时,可以提供一个超时时限(以毫秒为单位)用于指定等待多长时间后终止测试,默认为 5 秒。你也可以通过 [testTimeout](/config/#testtimeout) 选项进行全局配置。 - - ```ts - import { assert, test } from 'vitest' - - test.only('test', () => { - // 仅运行此测试(以及仅标记有的其他测试) - assert.equal(Math.sqrt(4), 2) - }) - ``` - - 有时候只运行一个特定文件中的 `only` 测试用例是很有用的,这可以忽略整个测试套件中的所有其他测试用例,避免污染输出。 - - 为了做到这一点,运行 `vitest` 命令并带上包含有问题的测试的特定文件。 - - ``` - # vitest interesting.test.ts - ``` -======= Use `test.only` to only run certain tests in a given suite. This is useful when debugging. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before terminating. The default is 5 seconds, and can be configured globally with [testTimeout](/config/#testtimeout). @@ -287,38 +177,16 @@ test.only('test', () => { Sometimes it is very useful to run `only` tests in a certain file, ignoring all other tests from the whole test suite, which pollute the output. In order to do that run `vitest` with specific file containing the tests in question. + ``` # vitest interesting.test.ts ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### test.concurrent -- **类型:** `(name: string | Function, fn: TestFunction, timeout?: number) => void` -- **别名:** `it.concurrent` - -<<<<<<< HEAD - `test.concurrent` 将连续测试标记为并行运行。 它接收测试名称、带有要收集的测试的异步函数以及可选的超时时间(以毫秒为单位)。 - - ```ts - import { describe, test } from 'vitest' - - // 标有并发的两个测试将并发运行 - describe('suite', () => { - test('serial test', async () => { - /* ... */ - }) - test.concurrent('concurrent test 1', async () => { - /* ... */ - }) - test.concurrent('concurrent test 2', async () => { - /* ... */ - }) - }) - ``` +- **Type:** `(name: string | Function, fn: TestFunction, timeout?: number) => void` +- **Alias:** `it.concurrent` - `test.skip`、`test.only` 和 `test.todo` 适用于并发测试。 以下所有组合均有效: -======= `test.concurrent` marks consecutive tests to be run in parallel. It receives the test name, an async function with the tests to collect, and an optional timeout (in milliseconds). ```ts @@ -326,14 +194,19 @@ import { describe, test } from 'vitest' // The two tests marked with concurrent will be run in parallel describe('suite', () => { - test('serial test', async () => { /* ... */ }) - test.concurrent('concurrent test 1', async () => { /* ... */ }) - test.concurrent('concurrent test 2', async () => { /* ... */ }) + test('serial test', async () => { + /* ... */ + }) + test.concurrent('concurrent test 1', async () => { + /* ... */ + }) + test.concurrent('concurrent test 2', async () => { + /* ... */ + }) }) ``` `test.skip`, `test.only`, and `test.todo` works with concurrent tests. All the following combinations are valid: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts test.concurrent(/* ... */) @@ -342,13 +215,8 @@ test.only.concurrent(/* ... */) // or test.concurrent.only(/* ... */) test.todo.concurrent(/* ... */) // or test.concurrent.todo(/* ... */) ``` -<<<<<<< HEAD - 在异步并发测试中使用快照时,由于 JavaScript 的限制,你需要使用 [测试环境](/guide/test-context.md) 中的 `expect` 来确保检测到正确的测试。 -======= When running concurrent tests, Snapshots and Assertions must use `expect` from the local [Test Context](/guide/test-context.md) to ensure the right test is detected. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 - ```ts test.concurrent('test 1', async ({ expect }) => { expect(foo).toMatchSnapshot() @@ -359,49 +227,26 @@ test.concurrent('test 2', async ({ expect }) => { ``` ::: warning -当 Vitest 作为 [类型检查器](/guide/testing-types) 时,你不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ### test.todo -- **类型:** `(name: string | Function) => void` -- **别名:** `it.todo` - -<<<<<<< HEAD - 使用 `test.todo` 来存根测试,以便稍后实现。 测试报告中将显示一个条目,以便告知你还有多少测试未实现。 +- **Type:** `(name: string | Function) => void` +- **Alias:** `it.todo` - ```ts - // 测试的报告中将显示一个记录 - test.todo('unimplemented test') - ``` -======= Use `test.todo` to stub tests to be implemented later. An entry will be shown in the report for the tests so you know how many tests you still need to implement. ```ts // An entry will be shown in the report for this test test.todo('unimplemented test') ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### test.fails -- **类型:** `(name: string | Function, fn: TestFunction, timeout?: number) => void` -- **别名:** `it.fails` +- **Type:** `(name: string | Function, fn: TestFunction, timeout?: number) => void` +- **Alias:** `it.fails` -<<<<<<< HEAD - 使用 `test.fails` 来指示测试断言将显式失败。 - - ```ts - import { expect, test } from 'vitest' - - function myAsyncFunc() { - return new Promise(resolve => resolve(1)) - } - test.fails('fail test', async () => { - await expect(myAsyncFunc()).rejects.toBe(1) - }) - ``` -======= Use `test.fails` to indicate that an assertion will fail explicitly. ```ts @@ -414,30 +259,16 @@ test.fails('fail test', async () => { await expect(myAsyncFunc()).rejects.toBe(1) }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ::: warning -当 Vitest 作为 [类型检查器](/guide/testing-types) 时,你不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ### test.each -- **类型:** `(cases: ReadonlyArray, ...args: any[]) => void` -- **别名:** `it.each` - -<<<<<<< HEAD - 当你需要使用不同的变量运行相同的测试时,请使用 `test.each`。 - 你可以按照测试参数的顺序,在测试名称插入符合[printf 格式](https://nodejs.org/api/util.html#util_util_format_format_args)的参数。 - - - `%s`: 字符串 - - `%d`: 数值 - - `%i`: 整数 - - `%f`: 小数 - - `%j`: json 格式 - - `%o`: 对象 - - `%#`: 对应的测试参数下标 - - `%%`: 单个百分比符号 ('%') -======= +- **Type:** `(cases: ReadonlyArray, ...args: any[]) => void` +- **Alias:** `it.each` + Use `test.each` when you need to run the same test with different variables. You can inject parameters with [printf formatting](https://nodejs.org/api/util.html#util_util_format_format_args) in the test name in the order of the test function parameters. @@ -466,50 +297,16 @@ test.each([ ``` You can also access object properties with `$` prefix, if you are using objects as arguments: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 - - ```ts - test.each([ - { a: 1, b: 1, expected: 2 }, - { a: 1, b: 2, expected: 3 }, - { a: 2, b: 1, expected: 3 }, - ])('add($a, $b) -> $expected', ({ a, b, expected }) => { - expect(a + b).toBe(expected) - }) -<<<<<<< HEAD - // 它将返回如下内容 - // ✓ add(1, 1) -> 2 - // ✓ add(1, 2) -> 3 - // ✓ add(2, 1) -> 3 - ``` - - 如果你使用对象作为参数,你还可以使用 `$` 前缀访问对象属性: - - ```ts - test.each([ - { a: 1, b: 1, expected: 2 }, - { a: 1, b: 2, expected: 3 }, - { a: 2, b: 1, expected: 3 }, - ])('add($a, $b) -> $expected', ({ a, b, expected }) => { - expect(a + b).toBe(expected) - }) +```ts +test.each([ + { a: 1, b: 1, expected: 2 }, + { a: 1, b: 2, expected: 3 }, + { a: 2, b: 1, expected: 3 }, +])('add($a, $b) -> $expected', ({ a, b, expected }) => { + expect(a + b).toBe(expected) +}) - // this will return - // ✓ add(1, 1) -> 2 - // ✓ add(1, 2) -> 3 - // ✓ add(2, 1) -> 3 - ``` - - 如果你使用对象作为参数,你还可以使用“.”访问对象属性: - - ```ts - test.each` - a | b | expected - ${{ val: 1 }} | ${'b'} | ${'1b'} - ${{ val: 2 }} | ${'b'} | ${'2b'} - ${{ val: 3 }} | ${'b'} | ${'3b'} -======= // this will return // ✓ add(1, 1) -> 2 // ✓ add(1, 2) -> 3 @@ -518,28 +315,26 @@ You can also access object properties with `$` prefix, if you are using objects You can also access Object attributes with `.`, if you are using objects as arguments: - ```ts - test.each` - a | b | expected - ${{ val: 1 }} | ${'b'} | ${'1b'} - ${{ val: 2 }} | ${'b'} | ${'2b'} - ${{ val: 3 }} | ${'b'} | ${'3b'} ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 - `('add($a.val, $b) -> $expected', ({ a, b, expected }) => { - expect(a.val + b).toBe(expected) - }) +```ts +test.each` + a | b | expected + ${{ val: 1 }} | ${'b'} | ${'1b'} + ${{ val: 2 }} | ${'b'} | ${'2b'} + ${{ val: 3 }} | ${'b'} | ${'3b'} +`('add($a.val, $b) -> $expected', ({ a, b, expected }) => { + expect(a.val + b).toBe(expected) +}) - // this will return - // ✓ add(1, b) -> 1b - // ✓ add(2, b) -> 2b - // ✓ add(3, b) -> 3b - ``` +// this will return +// ✓ add(1, b) -> 1b +// ✓ add(2, b) -> 2b +// ✓ add(3, b) -> 3b +``` -<<<<<<< HEAD -从 Vitest 0.25.3 开始,你可以使用模板字符串表。 +Starting from Vitest 0.25.3, you can also use template string table. -- 第一行应该是列名,使用 `|` 分隔; -- 使用 `${value}` 语法作为模板文本表达式,为一个或多个后续数据行提供数据。 +- First row should be column names, separated by `|`; +- One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. ```ts test.each` @@ -549,52 +344,32 @@ test.each` ${[]} | ${'b'} | ${'b'} ${{}} | ${'b'} | ${'[object Object]b'} ${{ asd: 1 }} | ${'b'} | ${'[object Object]b'} -======= -Starting from Vitest 0.25.3, you can also use template string table. - -* First row should be column names, separated by `|`; -* One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. - -```ts -test.each` - a | b | expected - ${1} | ${1} | ${2} - ${'a'} | ${'b'} | ${'ab'} - ${[]} | ${'b'} | ${'b'} - ${{}} | ${'b'} | ${'[object Object]b'} - ${{ asd: 1 }} | ${'b'} | ${'[object Object]b'} ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 `('returns $expected when $a is added $b', ({ a, b, expected }) => { expect(a + b).toBe(expected) }) ``` -<<<<<<< HEAD -如果你想访问 `TestContext`,请在单个测试中使用 `describe.each`。 -======= If you want to have access to `TestContext`, use `describe.each` with a single test. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ::: tip Vitest processes `$values` with chai `format` method. If the value is too truncated, you can increase [chaiConfig.truncateThreshold](/config/#chaiconfig-truncatethreshold) in your config file. ::: ::: warning -当使用 Vitest 作为 [type checker](/guide/testing-types) 时,不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ## bench -- **类型:** `(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void` +- **Type:** `(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void` -`bench` 定义了一个基准。 在 Vitest 术语中,基准是定义一系列操作的函数。 Vitest 多次运行此函数以显示不同的性能结果。 +`bench` defines a benchmark. In Vitest terms benchmark is a function that defines a series of operations. Vitest runs this function multiple times to display different performance results. -Vitest 在底层使用 [`tinybench`](https://github.com/tinylibs/tinybench) 库,继承其所有可用选项作为第三个参数。 +Vitest uses [`tinybench`](https://github.com/tinylibs/tinybench) library under the hood, inheriting all its options that can be used as a third argument. ```ts import { bench } from 'vitest' -<<<<<<< HEAD bench( 'normal sorting', () => { @@ -605,14 +380,6 @@ bench( }, { time: 1000 } ) -======= -bench('normal sorting', () => { - const x = [1, 5, 4, 2, 3] - x.sort((a, b) => { - return a - b - }) -}, { time: 1000 }) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ``` ```ts @@ -665,9 +432,9 @@ export interface Options { ### bench.skip -- **类型:** `(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void` +- **Type:** `(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void` -你可以使用 `bench.skip` 语法跳过运行某些基准测试。 +You can use `bench.skip` syntax to skip running certain benchmarks. ```ts import { bench } from 'vitest' @@ -682,9 +449,9 @@ bench.skip('normal sorting', () => { ### bench.only -- **类型:** `(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void` +- **Type:** `(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void` -使用 `bench.only` 仅在指定测试套件中运行某些基准测试。这在调试时很有用。 +Use `bench.only` to only run certain benchmarks in a given suite. This is useful when debugging. ```ts import { bench } from 'vitest' @@ -693,104 +460,6 @@ bench.only('normal sorting', () => { const x = [1, 5, 4, 2, 3] x.sort((a, b) => { return a - b -<<<<<<< HEAD - }) -}) -``` - -### bench.todo - -- **类型:** `(name: string | Function) => void` - -使用 `bench.todo` 来存根基准测试,以便稍后实现。 - -```ts -import { bench } from 'vitest' - -bench.todo('unimplemented test') -``` - -## describe - -当你在文件的顶层使用 `test` 或 `bench` 时,它们会被收集为它的隐式套件的一部分。 使用 `describe` 你可以在当前上下文中定义一个新套件,作为一组相关的测试或基准以及其他嵌套套件。 测试套件可让你组织测试和基准测试,从而使报告更加清晰。 - -```ts -// basic.spec.ts -// organizing tests - -import { describe, expect, test } from 'vitest' - -const person = { - isActive: true, - age: 32, -} - -describe('person', () => { - test('person is defined', () => { - expect(person).toBeDefined() - }) - - test('is active', () => { - expect(person.isActive).toBeTruthy() - }) - - test('age limit', () => { - expect(person.age).toBeLessThanOrEqual(32) - }) -}) -``` - -```ts -// basic.bench.ts -// organizing benchmarks - -import { bench, describe } from 'vitest' - -describe('sort', () => { - bench('normal', () => { - const x = [1, 5, 4, 2, 3] - x.sort((a, b) => { - return a - b - }) - }) - - bench('reverse', () => { - const x = [1, 5, 4, 2, 3] - x.reverse().sort((a, b) => { - return a - b - }) - }) -}) -``` - -如果你需要有测试层次结构,你还可以嵌套描述块: - -```ts -import { describe, expect, test } from 'vitest' - -function numberToCurrency(value) { - if (typeof value !== 'number') - throw new Error('Value must be a number') - - return value - .toFixed(2) - .toString() - .replace(/\B(?=(\d{3})+(?!\d))/g, ',') -} - -describe('numberToCurrency', () => { - describe('given an invalid number', () => { - test('composed of non-numbers to throw error', () => { - expect(() => numberToCurrency('abc')).toThrowError() - }) - }) - - describe('given a valid number', () => { - test('returns the correct currency format', () => { - expect(numberToCurrency(10000)).toBe('10,000.00') - }) - }) -======= }) }) ``` @@ -869,7 +538,10 @@ function numberToCurrency(value) { if (typeof value !== 'number') throw new Error('Value must be a number') - return value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') + return value + .toFixed(2) + .toString() + .replace(/\B(?=(\d{3})+(?!\d))/g, ',') } describe('numberToCurrency', () => { @@ -884,26 +556,13 @@ describe('numberToCurrency', () => { expect(numberToCurrency(10000)).toBe('10,000.00') }) }) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) ``` ### describe.skip -- **类型:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` +- **Type:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` -<<<<<<< HEAD - 在测试套件中使用 `describe.skip` 避免运行特定的描述块。 - - ```ts - import { assert, describe, test } from 'vitest' - - describe.skip('skipped suite', () => { - test('sqrt', () => { - // 跳过测试套件,不会有错误 - assert.equal(Math.sqrt(4), 3) - }) -======= Use `describe.skip` in a suite to avoid running a particular describe block. ```ts @@ -913,26 +572,14 @@ describe.skip('skipped suite', () => { test('sqrt', () => { // Suite skipped, no error assert.equal(Math.sqrt(4), 3) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) }) ``` ### describe.skipIf -- **类型:** `(condition: any) => void` - -<<<<<<< HEAD - 在某些情况下,你可能会在不同的环境中多次运行套件,并且某些套件可能是特定于环境的。你可以使用 `describe.skipIf` 在条件为真时跳过套件,而不是用 `if` 包装套件。 - -```ts -import { assert, test } from 'vitest' +- **Type:** `(condition: any) => void` -const isDev = process.env.NODE_ENV === 'development' - -test.skipIf(isDev)('prod only test', () => { - // 仅在生产中运行 -======= In some cases, you might run suites multiple times with different environments, and some of the suites might be environment-specific. Instead of wrapping the suite with `if`, you can use `describe.skipIf` to skip the suite whenever the condition is truthy. ```ts @@ -942,29 +589,21 @@ const isDev = process.env.NODE_ENV === 'development' describe.skipIf(isDev)('prod only test', () => { // this test only runs in production ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) ``` ::: warning -当 Vitest 作为 [类型检查器](/guide/testing-types) 时,你不能使用此语法。 +You cannot use this syntax when using Vitest as [type checker](/guide/testing-types). ::: ### describe.only -- **类型:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` - -<<<<<<< HEAD -使用 `describe.only` 仅运行指定的测试套件。 +- **Type:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` -```ts -// 仅运行此测试套件(以及仅标有的其他测试套件) -======= Use `describe.only` to only run certain suites ```ts // Only this suite (and others marked with only) are run ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 describe.only('suite', () => { test('sqrt', () => { assert.equal(Math.sqrt(4), 3) @@ -972,16 +611,6 @@ describe.only('suite', () => { }) describe('other suite', () => { -<<<<<<< HEAD - // ... 测试套件将会被跳过 -}) -``` - -有时候只运行一个特定文件中的 `only` 测试用例是很有用的,这可以忽略整个测试套件中的所有其他测试用例,避免污染输出。 - -为了做到这一点,运行 `vitest` 命令并带上包含有问题的测试的特定文件。 - -======= // ... will be skipped }) ``` @@ -989,48 +618,33 @@ describe('other suite', () => { Sometimes it is very useful to run `only` tests in a certain file, ignoring all other tests from the whole test suite, which pollute the output. In order to do that run `vitest` with specific file containing the tests in question. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 + ``` # vitest interesting.test.ts ``` ### describe.concurrent -- **类型:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` - -<<<<<<< HEAD - 使用 `describe.concurrent` 在测试套件中将每个测试标记为并发。 - - ```ts - // 该测试套件中的所有测试都将并行运行 - describe.concurrent('suite', () => { - test('concurrent test 1', async () => { - /* ... */ - }) - test('concurrent test 2', async () => { - /* ... */ - }) - test.concurrent('concurrent test 3', async () => { - /* ... */ - }) - }) - ``` +- **Type:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` - `.skip`,`.only` 和 `.todo` 可以与并发测试套件一起使用。以下所有组合均有效: -======= `describe.concurrent` in a suite marks every tests as concurrent ```ts // All tests within this suite will be run in parallel describe.concurrent('suite', () => { - test('concurrent test 1', async () => { /* ... */ }) - test('concurrent test 2', async () => { /* ... */ }) - test.concurrent('concurrent test 3', async () => { /* ... */ }) + test('concurrent test 1', async () => { + /* ... */ + }) + test('concurrent test 2', async () => { + /* ... */ + }) + test.concurrent('concurrent test 3', async () => { + /* ... */ + }) }) ``` `.skip`, `.only`, and `.todo` works with concurrent suites. All the following combinations are valid: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ```ts describe.concurrent(/* ... */) @@ -1039,7 +653,7 @@ describe.only.concurrent(/* ... */) // or describe.concurrent.only(/* ... */) describe.todo.concurrent(/* ... */) // or describe.concurrent.todo(/* ... */) ``` -在异步并发测试中使用快照时,由于 JavaScript 的限制,你需要使用 [测试环境](/guide/test-context.md) 中的 `expect` 来确保检测到正确的测试。 +When running concurrent tests, Snapshots and Assertions must use `expect` from the local [Test Context](/guide/test-context.md) to ensure the right test is detected. ```ts describe.concurrent('suite', () => { @@ -1053,134 +667,77 @@ describe.concurrent('suite', () => { ``` ::: warning -当 Vitest 作为 [类型检查器](/guide/testing-types) 时,你不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ### describe.sequential -- **类型:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` - -<<<<<<< HEAD - 测试套件中的 `describe.sequential` 将每个测试标记为连续的。如果你想在 `describe.concurrent` 中或使用 `--sequence.concurrent` 命令选项按顺序运行测试,这非常有用。 +- **Type:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` - ```ts - describe.concurrent('suite', () => { - test('concurrent test 1', async () => { - /* ... */ - }) - test('concurrent test 2', async () => { - /* ... */ - }) - - describe.sequential('', () => { - test('sequential test 1', async () => { - /* ... */ - }) - test('sequential test 2', async () => { - /* ... */ - }) - }) -======= `describe.sequential` in a suite marks every test as sequential. This is useful if you want to run tests in sequential within `describe.concurrent` or with the `--sequence.concurrent` command option. ```ts describe.concurrent('suite', () => { - test('concurrent test 1', async () => { /* ... */ }) - test('concurrent test 2', async () => { /* ... */ }) + test('concurrent test 1', async () => { + /* ... */ + }) + test('concurrent test 2', async () => { + /* ... */ + }) describe.sequential('', () => { - test('sequential test 1', async () => { /* ... */ }) - test('sequential test 2', async () => { /* ... */ }) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 + test('sequential test 1', async () => { + /* ... */ + }) + test('sequential test 2', async () => { + /* ... */ + }) }) }) ``` ### describe.shuffle -- **类型:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` - -<<<<<<< HEAD - Vitest 提供了一种通过 CLI 标志 [`--sequence.shuffle`](/guide/cli) 或配置选项 [`sequence.shuffle`](/config/#sequence-shuffle) 来随机运行所有测试的方法,但是如果你只想让测试套件的一部分以随机顺序运行测试,可以使用此标志对其进行标记。 +- **Type:** `(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void` - ```ts - describe.shuffle('suite', () => { - test('random test 1', async () => { - /* ... */ - }) - test('random test 2', async () => { - /* ... */ - }) - test('random test 3', async () => { - /* ... */ - }) - }) - // 执行顺序依赖于 sequence.seed 的配置选项(默认为 Date.now()) - ``` -======= Vitest provides a way to run all tests in random order via CLI flag [`--sequence.shuffle`](/guide/cli) or config option [`sequence.shuffle`](/config/#sequence-shuffle), but if you want to have only part of your test suite to run tests in random order, you can mark it with this flag. ```ts describe.shuffle('suite', () => { - test('random test 1', async () => { /* ... */ }) - test('random test 2', async () => { /* ... */ }) - test('random test 3', async () => { /* ... */ }) + test('random test 1', async () => { + /* ... */ + }) + test('random test 2', async () => { + /* ... */ + }) + test('random test 3', async () => { + /* ... */ + }) }) // order depends on sequence.seed option in config (Date.now() by default) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 -`.skip`,`.only` 和 `.todo` 可以与并发测试套件一起使用。以下所有组合均有效: +`.skip`, `.only`, and `.todo` works with random suites. ::: warning -当 Vitest 作为 [类型检查器](/guide/testing-types) 时,你不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ### describe.todo -- **类型:** `(name: string | Function) => void` - -<<<<<<< HEAD - 使用 `describe.todo` 将稍后实现的测试套件进行存档。测试报告中将显示一个记录,以便你知道还多少条未实现的测试。 +- **Type:** `(name: string | Function) => void` - ```ts - // 测试套件的报告中将显示一个记录 - describe.todo('unimplemented suite') - ``` -======= Use `describe.todo` to stub suites to be implemented later. An entry will be shown in the report for the tests so you know how many tests you still need to implement. ```ts // An entry will be shown in the report for this suite describe.todo('unimplemented suite') ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### describe.each -- **类型:** `(cases: ReadonlyArray, ...args: any[]): (name: string | Function, fn: (...args: T[]) => void, options?: number | TestOptions) => void` - -<<<<<<< HEAD - 如果你有多个测试依赖相同的数据,可以使用 `describe.each`。 +- **Type:** `(cases: ReadonlyArray, ...args: any[]): (name: string | Function, fn: (...args: T[]) => void, options?: number | TestOptions) => void` - ```ts - describe.each([ - { a: 1, b: 1, expected: 2 }, - { a: 1, b: 2, expected: 3 }, - { a: 2, b: 1, expected: 3 }, - ])('describe object add($a, $b)', ({ a, b, expected }) => { - test(`returns ${expected}`, () => { - expect(a + b).toBe(expected) - }) - - test(`returned value not be greater than ${expected}`, () => { - expect(a + b).not.toBeGreaterThan(expected) - }) - - test(`returned value not be less than ${expected}`, () => { - expect(a + b).not.toBeLessThan(expected) - }) -======= Use `describe.each` if you have more than one test that depends on the same data. ```ts @@ -1191,31 +748,10 @@ describe.each([ ])('describe object add($a, $b)', ({ a, b, expected }) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) -<<<<<<< HEAD - 从 Vitest 0.25.3 开始,你可以使用模板字符串表。 - - - 第一行应该是列名,使用 `|` 分隔; - - 使用 `${value}` 语法作为模板文本表达式,为一个或多个后续数据行提供数据。 - - ```ts - describe.each` - a | b | expected - ${1} | ${1} | ${2} - ${'a'} | ${'b'} | ${'ab'} - ${[]} | ${'b'} | ${'b'} - ${{}} | ${'b'} | ${'[object Object]b'} - ${{ asd: 1 }} | ${'b'} | ${'[object Object]b'} - `('describe template string add($a, $b)', ({ a, b, expected }) => { - test(`returns ${expected}`, () => { - expect(a + b).toBe(expected) - }) -======= test(`returned value not be greater than ${expected}`, () => { expect(a + b).not.toBeGreaterThan(expected) ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 }) test(`returned value not be less than ${expected}`, () => { @@ -1226,17 +762,17 @@ describe.each([ Starting from Vitest 0.25.3, you can also use template string table. -* First row should be column names, separated by `|`; -* One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. +- First row should be column names, separated by `|`; +- One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. ```ts describe.each` - a | b | expected - ${1} | ${1} | ${2} - ${'a'} | ${'b'} | ${'ab'} - ${[]} | ${'b'} | ${'b'} - ${{}} | ${'b'} | ${'[object Object]b'} - ${{ asd: 1 }} | ${'b'} | ${'[object Object]b'} + a | b | expected + ${1} | ${1} | ${2} + ${'a'} | ${'b'} | ${'ab'} + ${[]} | ${'b'} | ${'b'} + ${{}} | ${'b'} | ${'[object Object]b'} + ${{ asd: 1 }} | ${'b'} | ${'[object Object]b'} `('describe template string add($a, $b)', ({ a, b, expected }) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected) @@ -1245,51 +781,17 @@ describe.each` ``` ::: warning -当使用 Vitest 作为 [type checker](/guide/testing-types) 时,不能使用此语法。 +You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types). ::: ## Setup and Teardown -这些功能允许我们连接到测试的生命周期,以避免重复设置和拆卸代码。 它们适用于当前上下文:如果它们在顶层使用,则适用于文件;如果它们在 `describe` 块内,则适用于当前测试套件。 +These functions allow you to hook into the life cycle of tests to avoid repeating setup and teardown code. They apply to the current context: the file if they are used at the top-level or the current suite if they are inside a `describe` block. These hooks are not called, when you are running Vitest as a type checker. ### beforeEach -- **类型:** `beforeEach(fn: () => Awaitable, timeout?: number)` - -<<<<<<< HEAD - 注册一个回调,在当前上下文中的每个测试运行之前被调用。 - 如果函数返回一个 `Promise`,`Vitest` 会等到 `Promise` 解决后再运行测试。 - - 或者,我们可以传递一个超时(以毫秒为单位),定义在终止之前等待多长时间。 默认值为 5 秒。 +- **Type:** `beforeEach(fn: () => Awaitable, timeout?: number)` - ```ts - import { beforeEach } from 'vitest' - - beforeEach(async () => { - // 在每次测试运行之前清除模拟并添加一些测试数据 - await stopMocking() - await addUser({ name: 'John' }) - }) - ``` - - 这里的 `beforeEach` 确保为每个测试都添加用户。 - - 从 Vitest v0.10.0 开始,`beforeEach` 还接受一个可选的清理功能(相当于 `afterEach`)。 - - ```ts - import { beforeEach } from 'vitest' - - beforeEach(async () => { - // 在所有测试运行之前调用一次 - await prepareSomething() - - // 清理方法,在所有测试运行后调用一次 - return async () => { - await resetSomething() - } - }) - ``` -======= Register a callback to be called before each of the tests in the current context runs. If the function returns a promise, Vitest waits until the promise resolve before running the test. @@ -1322,28 +824,11 @@ beforeEach(async () => { } }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### afterEach -- **类型:** `afterEach(fn: () => Awaitable, timeout?: number)` - -<<<<<<< HEAD - 注册一个回调,在当前上下文中的每个测试运行之后被调用。 - 如果函数返回一个 Promise ,Vitest 会等到 Promise 解决后再继续。 +- **Type:** `afterEach(fn: () => Awaitable, timeout?: number)` - 或者,你可以设置超时(以毫秒为单位)以指定在终止前等待多长时间。 默认值为 5 秒。 - - ```ts - import { afterEach } from 'vitest' - - afterEach(async () => { - await clearTestingData() // 每次测试运行后清除测试数据 - }) - ``` - - 这里的 `afterEach` 确保在每次测试运行后清除测试数据。 -======= Register a callback to be called after each one of the tests in the current context completes. If the function returns a promise, Vitest waits until the promise resolve before continuing. @@ -1358,44 +843,11 @@ afterEach(async () => { ``` Here, the `afterEach` ensures that testing data is cleared after each test runs. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### beforeAll -- **类型:** `beforeAll(fn: () => Awaitable, timeout?: number)` - -<<<<<<< HEAD - 注册一个回调,在开始运行当前上下文中的所有测试之前被调用一次。 - 如果函数返回一个 `Promise`,`Vitest` 会等到 `Promise` 解决后再运行测试。 +- **Type:** `beforeAll(fn: () => Awaitable, timeout?: number)` - 或者,你可以提供超时(以毫秒为单位)以指定在终止之前等待多长时间。 默认值为 5 秒。 - - ```ts - import { beforeAll } from 'vitest' - - beforeAll(async () => { - await startMocking() // 在所有测试运行之前调用一次 - }) - ``` - - 这里的 `beforeAll` 确保在测试运行之前设置模拟数据。 - - 从 Vitest v0.10.0 开始,`beforeAll` 还可以接受一个可选的清理功能(相当于 `afterAll`)。 - - ```ts - import { beforeAll } from 'vitest' - - beforeAll(async () => { - // 在所有测试运行之前调用一次 - await startMocking() - - // 清理函数,在所有测试运行后调用一次 - return async () => { - await stopMocking() - } - }) - ``` -======= Register a callback to be called once before starting to run all tests in the current context. If the function returns a promise, Vitest waits until the promise resolve before running tests. @@ -1426,28 +878,11 @@ beforeAll(async () => { } }) ``` ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 ### afterAll -- **类型:** `afterAll(fn: () => Awaitable, timeout?: number)` - -<<<<<<< HEAD - 注册一个回调,在当前上下文中运行所有测试后被调用一次。 - 如果函数返回一个 Promise,Vitest 会等到 Promise 解决后再继续。 - - 或者,你可以提供超时(以毫秒为单位)以指定在终止之前等待多长时间。 默认值为 5 秒。 - - ```ts - import { afterAll } from 'vitest' - - afterAll(async () => { - await stopMocking() // 在所有测试运行后调用此方法 - }) - ``` +- **Type:** `afterAll(fn: () => Awaitable, timeout?: number)` -这里的 `afterAll` 确保在所有测试运行后调用 `stopMocking` 方法。 -======= Register a callback to be called once after all tests have run in the current context. If the function returns a promise, Vitest waits until the promise resolve before continuing. @@ -1462,4 +897,3 @@ afterAll(async () => { ``` Here the `afterAll` ensures that `stopMocking` method is called after all tests run. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 diff --git a/config/index.md b/config/index.md index 317a63de..0199f658 100644 --- a/config/index.md +++ b/config/index.md @@ -1443,10 +1443,10 @@ export interface BrowserProvider { #### browser.providerOptions -- **Type:** `BrowserProviderOptions` -- **Version:** Since Vitest 1.0.0-beta.3 +- **类型:** `BrowserProviderOptions` +- **版本:** Since Vitest 1.0.0-beta.3 -Options that will be passed down to provider when calling `provider.initialize`. +调用 `provider.initialize` 时将传递给提供程序的选项。 ```ts export default defineConfig({ @@ -1463,7 +1463,7 @@ export default defineConfig({ ``` ::: tip -To have a better type safety when using built-in providers, you can add one of these types (for provider that you are using) to your tsconfig's `compilerOptions.types` field: +为了在使用内置提供程序时获得更好的类型安全性,你可以将以下类型之一(针对正在使用的提供程序)添加到 tsconfig 的 `compilerOptions.types` 字段中: ```json { @@ -1480,27 +1480,15 @@ To have a better type safety when using built-in providers, you can add one of t #### browser.slowHijackESM -<<<<<<< HEAD - **类型:** `boolean` -- **默认值:** `true` -- **版本:** Vitest 0.31.0 -======= -- **Type:** `boolean` -- **Default:** `false` -- **Version:** Since Vitest 0.31.0 ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 +- **默认值:** `false` +- **版本:** Since Vitest 0.31.0 在 Node.js 中运行测试时,Vitest 可以使用自己的模块解析来轻松地使用 `vi.mock` 语法模拟模块。但是,在浏览器中复制 ES 模块解析并不容易,因此我们需要在浏览器可以使用它之前转换您的源文件。 -<<<<<<< HEAD 此选项对在 Node.js 中运行的测试没有影响。 -在浏览器中运行时,默认情况下启用此选项。如果您不依赖使用 `vi.spyOn` 监视 ES 模块并且不使用 `vi.mock`,则可以禁用此选项以获得轻微的性能提升。 -======= -This option has no effect on tests running inside Node.js. - -If you rely on spying on ES modules with `vi.spyOn`, you can enable this experimental feature to allow spying on module exports. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 +在浏览器中运行时,默认情况下会启用此选项。如果你依赖于使用 `vi.spyOn` 监视 ES 模块,则可以启用此实验功能来监视模块导出。 ### clearMocks diff --git a/guide/migration.md b/guide/migration.md index 9598f3d0..02339c36 100644 --- a/guide/migration.md +++ b/guide/migration.md @@ -20,7 +20,8 @@ Jest 默认启用[全局 API](https://jestjs.io/zh-Hans/docs/api)。然而 Vites ```ts jest.mock('./some-path', () => 'hello') // [!code --] -vi.mock('./some-path', () => ({ // [!code ++] +vi.mock('./some-path', () => ({ + // [!code ++] default: 'hello', // [!code ++] })) // [!code ++] ``` @@ -50,7 +51,7 @@ Jest 导出各种 [`jasmine`](https://jasmine.github.io/) 全局 API (例如 `ja ### Replace property -如果你想修改测试环境,你会在 Jest 中使用 [replaceProperty API](https://jestjs.io/docs/jest-object#jestreplacepropertyobject-propertykey-value),你可以使用 [vi.stubEnv](https://cn.vitest.dev/api/vi.html#vi-stubenv) 或者 [`vi.spyOn`](/api/vi#vi-spyon) 也可以在 Vitest 中执行此操作。 +如果你想修改测试环境,你会在 Jest 中使用 [replaceProperty API](https://jestjs.io/docs/jest-object#jestreplacepropertyobject-propertykey-value),你可以使用 [vi.stubEnv](https://cn.vitest.dev/api/vi.html#vi-stubenv) 或者 [`vi.spyOn`](/api/vi#vi-spyon) 也可以在 Vitest 中执行此操作。 ### 回调完成 @@ -71,7 +72,9 @@ it('should work', () => new Promise(done => { // [!code ++] ```ts beforeEach(() => setActivePinia(createTestingPinia())) // [!code --] -beforeEach(() => { setActivePinia(createTestingPinia()) }) // [!code ++] +beforeEach(() => { + setActivePinia(createTestingPinia()) +}) // [!code ++] ``` In Jest hooks are called sequentially (one after another). By default, Vitest runs hooks in parallel. To use Jest's behavior, update [`sequence.hooks`](/config/#sequence-hooks) option: @@ -79,20 +82,17 @@ In Jest hooks are called sequentially (one after another). By default, Vitest ru ```ts export default defineConfig({ test: { - sequence: { // [!code ++] + sequence: { + // [!code ++] hooks: 'list', // [!code ++] - } // [!code ++] - } + }, // [!code ++] + }, }) ``` ### 类型 -<<<<<<< HEAD -Vitest 没有在 `Vi` 命名空间上导出很多类型,它的存在主要是为了与匹配器兼容,因此你可能需要直接从 `vitest` 导入类型,而不是依赖 `Vi` 命名空间: -======= -Vitest doesn't have an equivalent to `jest` namespace, so you will need to import types directly from `vitest`: ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 +Vitest 没有等效于 `jest` 的命名空间,因此你需要直接从 `Vitest` 导入类型: ```ts // [!code --] @@ -110,6 +110,7 @@ let fn: Mock<[string], string> // [!code ++] jest.setTimeout(5_000) // [!code --] vi.setConfig({ testTimeout: 5_000 }) // [!code ++] ``` + ### Vue 快照 如果你以前在 vue-cli preset 中使用 Jest,那么这不是一个 Jest 独有的新特性。你可能需要安装 [`jest-serializer-vue`](https://github.com/eddyerburgh/jest-serializer-vue) 包,然后在 [setupFiles](/config/#setupfiles) 中配置: diff --git a/guide/snapshot.md b/guide/snapshot.md index aa03759c..f27e39c2 100644 --- a/guide/snapshot.md +++ b/guide/snapshot.md @@ -230,6 +230,8 @@ test('toThrowErrorMatchingSnapshot', () => { }) ``` +“toThrowErrorMatchingSnapshot”和“toThrow ErrorMatchingInlineSnapshot”的默认“错误”快照不同` + 在 Jest 中,快照将是: ```console @@ -242,7 +244,7 @@ exports[`toThrowErrorMatchingSnapshot: hint 1`] = `"error"`; exports[`toThrowErrorMatchingSnapshot > hint 1`] = `[Error: error]`; ``` -#### 4. default `Error` snapshot is different for `toThrowErrorMatchingSnapshot` and `toThrowErrorMatchingInlineSnapshot` +#### 4. `toThrowErrorMatchingSnapshot` 和 `toThrowErrorMatchingInlineSnapshot` 的默认 `Error` 快照不同 ```js test('snapshot', () => { @@ -250,21 +252,21 @@ test('snapshot', () => { // in Jest // - expect(new Error('error')).toMatchInlineSnapshot(`[Error: error]`) + expect(new Error('error')).toMatchInlineSnapshot('[Error: error]') // Jest snapshots `Error.message` for `Error` instance expect(() => { throw new Error('error') - }).toThrowErrorMatchingInlineSnapshot(`"error"`) + }).toThrowErrorMatchingInlineSnapshot('"error"') // // in Vitest // - expect(new Error('error')).toMatchInlineSnapshot(`[Error: error]`) + expect(new Error('error')).toMatchInlineSnapshot('[Error: error]') expect(() => { throw new Error('error') - }).toThrowErrorMatchingInlineSnapshot(`[Error: error]`) + }).toThrowErrorMatchingInlineSnapshot('[Error: error]') }) ``` diff --git a/index.md b/index.md index 5113c2a7..7692c66b 100644 --- a/index.md +++ b/index.md @@ -27,27 +27,16 @@ hero: link: https://github.com/vitest-dev/vitest features: -<<<<<<< HEAD - title: 基于Vite驱动 + icon: details: 可以重用Vite的配置和插件,使得应用程序和测试保持一致。但是使用Vitest并不需要使用Vite! - title: 与Jest兼容 + icon: details: 支持Expect断言、快照测试、覆盖率等功能,从Jest迁移过来非常简单。 - title: 智能且即时的监视模式 + icon: ⚡ details: 只重新运行相关的更改,就像测试的热模块重载一样! - title: ESM、TypeScript、JSX支持 - details: 内置ESM、TypeScript和JSX支持,由esbuild提供动力。 -======= - - title: Vite Powered - icon: - details: Reuse Vite's config and plugins - consistent across your app and tests. But it's not required to use Vitest! - - title: Jest Compatible - icon: - details: Expect, snapshot, coverage, and more - migrating from Jest is straightforward. - - title: Smart & instant watch mode - icon: ⚡ - details: Only rerun the related changes, just like HMR for tests! - - title: ESM, TypeScript, JSX icon: - details: Out-of-box ESM, TypeScript and JSX support powered by esbuild. ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 + details: 内置ESM、TypeScript和JSX支持,由esbuild提供动力。 --- diff --git a/package.json b/package.json index f8e3b42a..52fdb719 100644 --- a/package.json +++ b/package.json @@ -24,12 +24,9 @@ "@antfu/eslint-config": "^0.35.3", "@antfu/ni": "^0.18.8", "@iconify-json/carbon": "^1.1.21", -<<<<<<< HEAD + "@iconify-json/logos": "^1.1.37", "@types/fs-extra": "^11.0.1", "@types/node": "^18.11.18", -======= - "@iconify-json/logos": "^1.1.37", ->>>>>>> 4be1f32f7b1f40c6c8d7f479bcb751276ae29f47 "@unocss/reset": "^0.53.4", "@vite-pwa/assets-generator": "^0.0.10", "@vite-pwa/vitepress": "^0.2.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7012d359..d57f4a76 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -22,6 +22,9 @@ devDependencies: '@iconify-json/carbon': specifier: ^1.1.21 version: 1.1.21 + '@iconify-json/logos': + specifier: ^1.1.37 + version: 1.1.37 '@types/fs-extra': specifier: ^11.0.1 version: 11.0.1 @@ -2024,6 +2027,12 @@ packages: '@iconify/types': 2.0.0 dev: true + /@iconify-json/logos@1.1.37: + resolution: {integrity: sha512-H2S8frTEznk6paX2kMzeUGn4KSiykghvO0b8UvEDd1fFFzt0WxCXpP1tBv67XaWK99e6JgA34hhv4lRGAm1hJg==} + dependencies: + '@iconify/types': 2.0.0 + dev: true + /@iconify/types@2.0.0: resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==} dev: true