Skip to content

Commit

Permalink
Merge pull request #337 from vitest-dev/sync-f204bb76-1
Browse files Browse the repository at this point in the history
docs(en): merge docs-cn/sync-docs into docs-cn/dev @ f204bb7
  • Loading branch information
elonehoo authored Nov 13, 2023
2 parents 80ce50f + 921008f commit f357eab
Show file tree
Hide file tree
Showing 10 changed files with 596 additions and 204 deletions.
13 changes: 9 additions & 4 deletions .vitepress/contributor-names.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"AriPerkkio",
"patak-dev",
"userquin",
"Dunqing",
"Demivan",
"Aslemammad",
"Dunqing",
"btea",
"poyoho",
"DerYeger",
Expand Down Expand Up @@ -36,17 +36,18 @@
"danez",
"horacioh",
"JessicaSachs",
"marcelobotega",
"pd4d10",
"narutosstudent",
"trivikr",
"azaleta",
"dsyddall",
"haikyuu",
"aleclarson",
"ouduidui",
"ghiscoding",
"kalvenschraut",
"LoTwT",
"marcelobotega",
"leonardssh",
"nickmccurdy",
"sachinraja",
Expand All @@ -64,7 +65,9 @@
"hannoeru",
"jgoux",
"thebanjomatic",
"adriencaccia",
"cawa-93",
"allisons11",
"anthonyblond",
"azrikahar",
"benmccann",
Expand All @@ -77,6 +80,7 @@
"Akryum",
"hamirmahal",
"sodatea",
"hi-ogawa",
"IanVS",
"InfiniteXyy",
"JakeGinnivan",
Expand Down Expand Up @@ -119,7 +123,6 @@
"atk",
"Codex-",
"abereghici",
"allisons11",
"aktyw",
"datsenkoboos",
"ArtyMaury",
Expand Down Expand Up @@ -185,7 +188,7 @@
"cometkim",
"IKoshelev",
"cogor",
"maIIady",
"Ilanaya",
"cliarena",
"beckjake",
"jcbhmr",
Expand Down Expand Up @@ -228,6 +231,7 @@
"luismartinezs",
"lukashass",
"lyx-jay",
"macklinu",
"malkiii",
"brzezinskimarcin",
"marcomuser",
Expand Down Expand Up @@ -342,6 +346,7 @@
"jonathan-graf",
"josefaidt",
"jp-liu",
"kare-rentelligent",
"lexmin0412",
"lxy-yz",
"mzanelee",
Expand Down
14 changes: 8 additions & 6 deletions .vitepress/scripts/fetch-avatars.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync, promises as fsp } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join, resolve } from 'pathe'
import fs from 'fs-extra'

const docsDir = resolve(dirname(fileURLToPath(import.meta.url)), '../..')

Expand All @@ -11,26 +11,28 @@ const dirSponsors = resolve(docsDir, 'public/sponsors/')
let contributors: string[] = []

async function download(url: string, fileName: string) {
if (fs.existsSync(fileName))
if (existsSync(fileName))
return
// eslint-disable-next-line no-console
console.log('downloading', fileName)
try {
const image = await (await fetch(url)).arrayBuffer()
await fs.writeFile(fileName, Buffer.from(image))
await fsp.writeFile(fileName, Buffer.from(image))
}
catch {}
}

async function fetchAvatars() {
await fs.ensureDir(dirAvatars)
contributors = JSON.parse(await fs.readFile(pathContributors, { encoding: 'utf-8' }))
if (!existsSync(dirAvatars))
await fsp.mkdir(dirAvatars, { recursive: true })
contributors = JSON.parse(await fsp.readFile(pathContributors, { encoding: 'utf-8' }))

await Promise.all(contributors.map(name => download(`https://github.com/${name}.png?size=100`, join(dirAvatars, `${name}.png`))))
}

async function fetchSponsors() {
await fs.ensureDir(dirSponsors)
if (!existsSync(dirSponsors))
await fsp.mkdir(dirSponsors, { recursive: true })
await Promise.all([
download('https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg', join(dirSponsors, 'antfu.svg')),
download('https://cdn.jsdelivr.net/gh/patak-dev/static/sponsors.svg', join(dirSponsors, 'patak-dev.svg')),
Expand Down
7 changes: 5 additions & 2 deletions config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -974,11 +974,14 @@ globalThis.resetBeforeEachTest = true

```ts
// globalSetup.js
// example.test.js
import { inject } from 'vitest'
export default function setup({ provide }) {
provide('wsPort', 3000)
}
```

```ts
// example.test.js
import { inject } from 'vitest'

inject('wsPort') === 3000
```
Expand Down
18 changes: 10 additions & 8 deletions guide/in-source.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,13 @@ if (import.meta.vitest) {
更新 Vitest 配置文件内的 `includeSource` 以获取到 `src/` 下的文件:

```ts
// vitest.config.ts
import { defineConfig } from 'vitest/config'
// vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'

export default defineConfig({
test: {
includeSource: ['src/**/*.{js,ts}'],
includeSource: ['src/**/*.{js,ts}'], // [!code ++]
},
})
```
Expand All @@ -55,16 +56,17 @@ $ npx vitest
对于生产环境的构建,你需要设置配置文件内的 `define` 选项,让打包器清除无用的代码。例如,在 Vite 中

```ts
// vitest.config.ts
import { defineConfig } from 'vitest/config'
// vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'

export default defineConfig({
test: {
includeSource: ['src/**/*.{js,ts}'],
},
define: { // [!code ++]
'import.meta.vitest': 'undefined', // [!code ++]
}, // [!code ++]
test: {
includeSource: ['src/**/*.{js,ts}']
},
})
```

Expand Down
2 changes: 1 addition & 1 deletion guide/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ bun add -D vitest
:::

:::tip
Vitest 需要 Vite >=v3.0.0 和 Node >=v14.18
Vitest 1.0 需要 Vite >=v5.0.0 和 Node >=v18.00
:::

建议你使用上面列出的方法之一在 `package.json` 中安装 `vitest` 的副本。 但是,如果你希望直接运行 `vitest`,可以使用 `npx vitest`(npm 和 Node.js 附带 `npx` 命令)。
Expand Down
2 changes: 1 addition & 1 deletion guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Jest 导出各种 [`jasmine`](https://jasmine.github.io/) 全局 API (例如 `ja

从 Vitest v0.10.0 开始,声明测试的回调样式被弃用。 你可以重写它们以使用 `async`/`await` 函数,或者使用 Promise 来模仿回调样式。

```ts
```
it('should work', (done) => { // [!code --]
it('should work', () => new Promise(done => { // [!code ++]
// ...
Expand Down
59 changes: 52 additions & 7 deletions guide/testing-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,62 @@ test('my types work properly', () => {

## 读取错误

如果你使用的是 `expectTypeOf` API,可能会注意到难以阅读的错误或意外的错误:
如果使用的是 `expectTypeOf` API,请参阅 [expect-type 关于其错误信息的文档](https://github.com/mmkal/expect-type#error-messages)

当类型不匹配时,`.toEqualTypeOf``.toMatchTypeOf`会使用一种特殊的辅助类型来生成尽可能可操作的错误信息。但要理解它们还有一些细微差别。由于断言是 "流畅地 "编写的,所以失败应该发生在 "预期 "类型上,而不是 "实际 "类型上(`expect<Actual>().toEqualTypeOf<Expected>()`)。这意味着类型错误可能有点令人困惑,因此该库生成了一个 `MismatchInfo` 类型,试图明确说明期望是什么。例如

```ts
expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: string }>()
```

是一个将失败的断言,因为 `{a: 1}` 的类型是 `{a: number}` 而不是 `{a: string}`。 这种情况下的错误信息如下

```
test/test.ts:999:999 - error TS2344: Type '{ a: string; }' does not satisfy the constraint '{ a: \\"Expected: string, Actual: number\\"; }'.
Types of property 'a' are incompatible.
Type 'string' is not assignable to type '\\"Expected: string, Actual: number\\"'.
999 expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>()
```

请注意,报告的类型约束是一个可读性强的消息,指定了"期望"和"实际"类型。不要字面上解读句子 `Types of property 'a' are incompatible // Type 'string' is not assignable to type "Expected: string, Actual: number"` ,而是看属性名(`'a'`)和消息内容:`Expected: string, Actual: number`。这将告诉你出了什么问题,在大多数情况下。当然,对于非常复杂的类型,调试可能需要更多的努力,并且可能需要一些试验。如果错误消息实际上是误导性的,请[提出问题](https://github.com/mmkal/expect-type)

对于像 `expectTypeOf(1).toBeString()` 这样的断言,`toBe...` 方法(如 `toBeString``toBeNumber``toBeVoid` 等)在被测试的 `Actual` 类型不匹配时会解析为一个不可调用的类型。例如,失败的断言可能会显示如下内容:

```
test/test.ts:999:999 - error TS2349: This expression is not callable.
Type 'ExpectString<number>' has no call signatures.
999 expectTypeOf(1).toBeString()
~~~~~~~~~~
```

这部分的`This expression is not callable`并没有太大的帮助 - 有意义的错误在下一行,`Type 'ExpectString<number> has no call signatures`。这基本上意味着你传递了一个数字,但断言它应该是一个字符串。

如果 TypeScript 添加了对 ["throw" 类型](https://github.com/microsoft/TypeScript/pull/40468) 的支持,这些错误消息将会显著改进。在那之前,它们需要一定程度的仔细观察。

#### 具体的 "expected "对象与类型参数

像这样的断言的错误消息:

```ts
expectTypeOf(1).toEqualTypeOf<string>()
// ^^^^^^^^^^^^^^^^^^^^^^
// index-c3943160.d.ts(90, 20): Arguments for the rest parameter 'MISMATCH' were not provided.
expectTypeOf({ a: 1 }).toEqualTypeOf({ a: '' })
```

这是由于 [`expect-type`](https://github.com/mmkal/expect-type) 处理类型错误的方式。
对于像这样的断言,错误消息将不够有帮助:

不幸的是,TypeScript 在不打补丁的情况下不提供类型元数据,因此我们目前无法提供有用的错误消息,但是有 <a href="https://github.com/microsoft/TypeScript/pull/40468" tatger=" _blank">在 TypeScript 项目中工作</a> 来解决这个问题。如果你想要更好的消息,请让 TypeScript 团队查看提到的 PR。
```ts
expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: string }>()
```

这是因为 TypeScript 编译器需要推断 `.toEqualTypeOf({a: ''})` 样式的类型参数,并且该库只能通过将其与通用的 `Mismatch` 类型进行比较来标记它为失败。因此,在可能的情况下,使用类型参数而不是具体类型来使用 `.toEqualTypeOf``toMatchTypeOf`。如果使用两个具体类型进行比较更加方便,可以使用 `typeof`

```ts
const one = valueFromFunctionOne({ some: { complex: inputs } })
const two = valueFromFunctionTwo({ some: { other: inputs } })

expectTypeOf(one).toEqualTypeof<typeof two>()
```

如果你发现很难使用 `expectTypeOf` API 并找出错误,你始终可以使用更简单的 `assertType` API:

Expand All @@ -54,7 +99,7 @@ assertType<string>(answer)
```

::: tip
使用 `@ts-expect-error` 语法时,你可能想确保没有输入错误。你可以通过在 [`test.include`](/config/#include) 配置选项中包含您的类型文件来做到这一点,因此 Vitest 实际上也会*运行*这些测试并因 `ReferenceError` 而失败。
使用 `@ts-expect-error` 语法时,你可能想确保没有输入错误。你可以通过在 [`test.include`](/config/#include) 配置选项中包含你的类型文件来做到这一点,因此 Vitest 实际上也会*运行*这些测试并因 `ReferenceError` 而失败。

这将通过,因为它预计会出现错误,但 “answer” 这个词有错别字,所以这是一个误报错误:

Expand Down
13 changes: 7 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
"serve": "vitepress serve",
"preview-https": "pnpm run build && serve .vitepress/dist",
"preview-https-no-prefetch": "pnpm run build-no-prefetch && serve .vitepress/dist",
"prefetch": "esno .vitepress/scripts/fetch-avatars.ts",
"prefetch": "tsx .vitepress/scripts/fetch-avatars.ts",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"generate-pwa-icons": "pwa-assets-generator"
},
"dependencies": {
"@vueuse/core": "^10.5.0",
"@vueuse/core": "^10.6.0",
"vue": "latest"
},
"devDependencies": {
Expand All @@ -33,8 +33,9 @@
"@vitejs/plugin-vue": "latest",
"eslint": "^8.34.0",
"esno": "^0.17.0",
"fast-glob": "^3.3.1",
"fast-glob": "^3.3.2",
"fs-extra": "^11.1.1",
"tsx": "^4.1.1",
"https-localhost": "^4.7.1",
"ofetch": "^1.3.3",
"ohmyfetch": "^0.4.21",
Expand All @@ -43,9 +44,9 @@
"typescript": "5.0.4",
"unocss": "^0.53.4",
"unplugin-vue-components": "^0.25.2",
"vite": "^4.5.0",
"vite-plugin-pwa": "^0.16.6",
"vitepress": "^1.0.0-rc.24",
"vite": "^5.0.0-beta.15",
"vite-plugin-pwa": "^0.16.7",
"vitepress": "^1.0.0-rc.25",
"workbox-window": "^7.0.0"
}
}
Loading

0 comments on commit f357eab

Please sign in to comment.