Skip to content

Commit

Permalink
Improve tests documentation (DefinitelyTyped#49636)
Browse files Browse the repository at this point in the history
Co-authored-by: Eli Barzilay <eli@barzilay.org>

Co-authored-by: Eli Barzilay <eli@barzilay.org>
  • Loading branch information
jablko and elibarzilay authored Nov 18, 2020
1 parent 09bc384 commit eee07ad
Show file tree
Hide file tree
Showing 7 changed files with 272 additions and 120 deletions.
5 changes: 2 additions & 3 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ Please fill in this template.

- [ ] Use a meaningful title for the pull request. Include the name of the package modified.
- [ ] Test the change in your own code. (Compile and run.)
- [ ] Add or edit tests to reflect the change. (Run with `npm test YOUR_PACKAGE_NAME`.)
- [ ] [Add or edit tests](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#my-package-teststs) to reflect the change.
- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes).
- [ ] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present).
- [ ] [Run `npm test <package to test>`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#running-tests).

Select one of these and delete the others:

Expand All @@ -20,7 +20,6 @@ If adding a new definition:
If changing an existing definition:
- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <<url here>>
- [ ] If this PR brings the type definitions up to date with a new version of the JS library, update the version number in the header.
- [ ] Include [tests for your changes](https://github.com/DefinitelyTyped/DefinitelyTyped#testing)
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`. If for reason the any rule need to be disabled, disable it for that line using `// tslint:disable-next-line [ruleName]` and not for whole package so that the need for disabling can be reviewed.

If removing a declaration:
Expand Down
52 changes: 45 additions & 7 deletions README.cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- [常见错误](#常见错误)
- [删除一个包](#删除一个包)
- [Linter](#linter)
- [<my package>-tests.ts](#my-package-teststs)
- [验证](#验证)
</details>
- [Definition Owners](#definition-owners)
Expand Down Expand Up @@ -143,8 +144,8 @@ Version | Released | End of Support

#### 编辑一个现有包

* `cd types/my-package-to-edit`
* 作出修改之后,记得新增测试。
* `cd types/<package to edit>`
* 作出修改之后,[记得新增测试](#my-package-teststs)
如果你进行了重大修改,不要忘记 [更新主版本](#if-a-library-is-updated-to-a-new-major-version-with-breaking-changes-how-should-i-update-its-type-declaration-package)
* 你可能还想将自己添加到包头部的 "Definitions by" 部分。
- 这会导致一旦有人对该包发起 PR 或者 issue,都会通知你(通过你的 GitHub 用户名)。
Expand All @@ -156,7 +157,7 @@ Version | Released | End of Support
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* 如果这里有 `tslint.json` 文件,就运行 `npm run lint package-name`。否则,在包目录里运行 `tsc`.
* [就运行 `npm test <package to test>`](#验证).

当你对现有的包发起 PR 的时候,请确保 `dt-bot` 会通知以前的作者。
如果没有,你可以在与 PR 关联的评论中手动去 @ 他们。
Expand All @@ -174,11 +175,11 @@ Version | Released | End of Support
| 文件名 | 目的 |
| --- | --- |
| index.d.ts | 这里包含了包的类型声明。 |
| foo-tests.ts | 这里包含了测试类型的示例代码,此代码 **不会** 运行,但是它需要通过类型检查。 |
| [<my package>-tests.ts](#my-package-teststs) | 这里包含了测试类型的示例代码,此代码 **不会** 运行,但是它需要通过类型检查。 |
| tsconfig.json | 这里允许你在包里运行 `tsc`. |
| tslint.json | 启用 linting. |

如果你的 npm ≥ 5.2.0,运行 `npx dts-gen --dt --name my-package-name --template module` 来生成这些文件,否则就运行 `npm install -g dts-gen``dts-gen --dt --name my-package-name --template module`.
如果你的 npm ≥ 5.2.0,运行 `npx dts-gen --dt --name <my package> --template module` 来生成这些文件,否则就运行 `npm install -g dts-gen``dts-gen --dt --name <my package> --template module`.
可以在 [dts-gen](https://github.com/Microsoft/dts-gen) 查看所有的选项。

你可以编辑 `tsconfig.json` 来增加新文件,增加 `"target": "es6"` (异步函数需要),去增加 `"lib"`,或者增加 `"jsx"` 编译选项。
Expand Down Expand Up @@ -220,7 +221,7 @@ Definitely Typed 的成员会定期查看新的 PRs,但是请记住当有许
- `libraryName`: 替换 Definitely Typed 中类型的 npm 的包名。通常这与 "typingsPackageName" 相同,这种情况下你可以忽略它。
Definitely Typed 中其他引用了删除包的任何包,都需要去更新去引用新的捆绑类型。
你可以查看 `npm run test` 中的错误来获得此列表。
你可以查看 `npm test` 中的错误来获得此列表。
添加一个带有 `"dependencies": { "foo": "x.y.z" }``package.json` 文件,去修复这些错误。
比如:
Expand Down Expand Up @@ -259,6 +260,43 @@ Definitely Typed 中其他引用了删除包的任何包,都需要去更新去
(若要使某个 lint 规则不生效,可以使用 `// tslint:disable rule-name`,当然使用 `//tslint:disable-next-line rule-name` 更好。)

#### <my package>-tests.ts

There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.

Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`

For example, this change to a function in a `.d.ts` file adding a new param to a function:

`index.d.ts`:

```diff
- export function twoslash(body: string): string
+ export function twoslash(body: string, config?: { version: string }): string
```

`<my package>-tests.ts`:

```diff
import {twoslash} from "./"
// $ExpectType string
const result = twoslash("//")
+ // Handle options param
+ const resultWithOptions = twoslash("//", { version: "3.7" })
+ // When the param is incorrect
+ // $ExpectError
+ const resultWithOptions = twoslash("//", { })
```

If you're wondering where to start with test code, the examples in the README of the module are a great place to start.

You can [validate your changes](#验证) with `npm test <package to test>` from the root of this repo, which takes changed files into account.

若要声明的表达式是一个给定类型,请使用 `$ExpectType`. 若要声明的表达式会导致编译错误,请使用 `$ExpectError`.

```js
Expand All @@ -273,7 +311,7 @@ f("one");

#### 验证

通过运行 `npm run lint package-name` 去测试你的改动,其中 `package-name` 是你的包名。
通过运行 `npm test <package to test>` 去测试你的改动,其中 `<package to test>` 是你的包名。
这个脚本使用了 [dtslint](https://github.com/Microsoft/dtslint).

### Definition Owners
Expand Down
53 changes: 47 additions & 6 deletions README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Vea también el sitio web [definitelytyped.org](http://definitelytyped.org), aun
- [Errores comunes](#errores-comunes)
- [Remover un paquete](#remover-un-paquete)
- [Lint](#lint)
- [<my package>-tests.ts](#my-package-teststs)
- [Running Tests](#running-tests)
</details>
- [Definition Owners](#definition-owners)
* [FAQ](#faq)
Expand Down Expand Up @@ -131,8 +133,8 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re

#### Editar un paquete existente

* `cd types/my-package-to-edit`
* Haz cambios. Recuerda editar las pruebas.
* `cd types/<package to edit>`
* Haz cambios. Recuerda [editar las pruebas](#my-package-teststs).
Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal).
* También puede que quieras añadirle la sección "Definitions by" en el encabezado del paquete.
- Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete.
Expand All @@ -144,7 +146,7 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Si hay un `tslint.json`, ejecuta `npm run lint package-name`. De lo contrario, ejecuta `tsc` en el directorio del paquete.
* [Ejecuta `npm test <package to test>`](#running-tests).

Cuando hagas un PR para editar un paquete existente, `dt-bot` deberá @-mencionar a los autores previos.
Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
Expand All @@ -163,11 +165,11 @@ Tu paquete debería tener esta estructura:
| Archivo | Propósito |
| --- | --- |
| index.d.ts | Este contiene los typings del paquete. |
| foo-tests.ts | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. |
| [<my package>-tests.ts](#my-package-teststs) | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. |
| tsconfig.json | Este permite ejecutar `tsc` dentro del paquete. |
| tslint.json | Permite linting. |

Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name my-package-name --template module`.
Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name <my package> --template module`.
Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen).

También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`.
Expand Down Expand Up @@ -229,6 +231,43 @@ Si el `tslint.json` deshabilita algunas reglas esto se debe a que aún no se ha

(Para indicar que la regla lint realmente no es utilizada, usa `// tslint:disable rule-name` o mejor, `//tslint:disable-next-line rule-name`.)

#### <my package>-tests.ts

There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.

Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`

For example, this change to a function in a `.d.ts` file adding a new param to a function:

`index.d.ts`:

```diff
- export function twoslash(body: string): string
+ export function twoslash(body: string, config?: { version: string }): string
```

`<my package>-tests.ts`:

```diff
import {twoslash} from "./"

// $ExpectType string
const result = twoslash("//")

+ // Handle options param
+ const resultWithOptions = twoslash("//", { version: "3.7" })
+ // When the param is incorrect
+ // $ExpectError
+ const resultWithOptions = twoslash("//", { })
```

If you're wondering where to start with test code, the examples in the README of the module are a great place to start.

You can [validate your changes](#running-tests) with `npm test <package to test>` from the root of this repo, which takes changed files into account.

Para afirmar que una expresión es de un tipo dado, utilice `$ExpectType`. Para afirmar que una expresión causa un error de compilación, utilice `$ExpectError`.

```js
Expand All @@ -241,7 +280,9 @@ f("one");

Para más detalles, vea el [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.

Realiza una prueba ejecutando `npm run lint package-name` donde `package-name` es el nombre de tu paquete.
#### Running Tests

Realiza una prueba ejecutando `npm test <package to test>` donde `<package to test>` es el nombre de tu paquete.
Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).

### Definition Owners
Expand Down
52 changes: 45 additions & 7 deletions README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- [많이 저지르는 실수들](#많이-저지르는-실수들)
- [패키지 삭제하기](#패키지-삭제하기)
- [린터](#린터)
- [<my package>-tests.ts](#my-package-teststs)
- [검증하기](#검증하기)
</details>
- [Definition Owners](#definition-owners)
Expand Down Expand Up @@ -154,8 +155,8 @@ Definitely Typed는 여러분과 같은 많은 기여자들의 도움 덕분에

#### 이미 존재하는 패키지를 수정하기

* `cd types/my-package-to-edit` 명령을 실행합니다.
* 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요!
* `cd types/<package to edit>` 명령을 실행합니다.
* 자료형(Typing) 파일들을 수정합니다. [테스트를 추가하는 것도 잊지마세요](#my-package-teststs)!
만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#패키지를-새-메이저-버전major-version에-맞게-갱신하고-싶어요)을 꼭 올려주세요.
* 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다.
- 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다.
Expand All @@ -167,7 +168,7 @@ Definitely Typed는 여러분과 같은 많은 기여자들의 도움 덕분에
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `tslint.json` 파일이 있는 경우에는, `npm run lint package-name` 명령을 실행시키고 결과를 확인해주세요. 그렇지 않은 경우에는, 해당 패키지가 있는 디렉토리 안에서 `tsc` 명령을 실행시키고 결과를 확인해주세요.
* [`npm test <package to test>` 명령을 실행시키고 결과를 확인해주세요](#검증하기).

이미 존재하는 패키지에 대한 풀 리퀘스트(Pull request)를 만들었을 경우에는, `dt-bot` 이 이전 저자들을 자동으로 호출하는지 확인해주세요.
그렇지 않은 경우에는, 여러분이 직접 풀 리퀘스트(Pull request)와 관계있는 사람들을 호출할 수도 있습니다.
Expand All @@ -186,12 +187,12 @@ NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지
| 파일 이름 | 용도 |
| --- | --- |
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| [<my package>-tests.ts](#my-package-teststs) | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |

이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name my-package-name --template module` 명령으로,
그 이하 경우에는 `npm install -g dts-gen``dts-gen --dt --name my-package-name --template module` 명령으로 만들 수 있습니다.
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name <my package> --template module` 명령으로,
그 이하 경우에는 `npm install -g dts-gen``dts-gen --dt --name <my package> --template module` 명령으로 만들 수 있습니다.
`dts-gen` 의 모든 옵션(Option)을 보고싶으시면 [dts-gen](https://github.com/Microsoft/dts-gen) 저장소를 확인해주세요.

자료형(Typing) 패키지에 새 파일을 추가하거나, `async` 키워드를 사용하기 위해 `"target"``"es6"` 로 설정하거나, `"lib"` 를 추가하거나, `jsx` 지원을 추가하기 위해서 `tsconfig.json` 파일을 변경해야 할 수도 있습니다.
Expand Down Expand Up @@ -254,6 +255,43 @@ Definitely Typed 에 한 번도 올라온 적 없는 패키지가 형(Type)을

(린트 규칙(Lint rule)이 절대로 적용되서는 안되는 경우에는, `// tslint:disable rule-name``//tslint:disable-next-line rule-name` 를 사용하는 것이 좋습니다. 후자가 더 나은 방식입니다.)

#### <my package>-tests.ts

There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.

Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`

For example, this change to a function in a `.d.ts` file adding a new param to a function:

`index.d.ts`:

```diff
- export function twoslash(body: string): string
+ export function twoslash(body: string, config?: { version: string }): string
```

`<my package>-tests.ts`:

```diff
import {twoslash} from "./"

// $ExpectType string
const result = twoslash("//")

+ // Handle options param
+ const resultWithOptions = twoslash("//", { version: "3.7" })
+ // When the param is incorrect
+ // $ExpectError
+ const resultWithOptions = twoslash("//", { })
```

If you're wondering where to start with test code, the examples in the README of the module are a great place to start.

You can [validate your changes](#검증하기) with `npm test <package to test>` from the root of this repo, which takes changed files into account.

어떤 표현식(Expression)이 특정한 형(Type)을 가진다고 단언(Assert)하고 싶을 때에는 `$ExpectType` 를 사용하시면 됩니다. 어떤 표현식(Expression)이 컴파일에 실패해야하는 경우에는 `$ExpectError` 를 하시면 됩니다.

```js
Expand All @@ -268,7 +306,7 @@ f("one");

#### 검증하기

`npm run lint package-name` 명령을 통해 변경점을 테스트할 수 있습니다. 이 때, `package-name`은 테스트하고 싶은 패키지의 이름입니다.
`npm test <package to test>` 명령을 통해 변경점을 테스트할 수 있습니다. 이 때, `<package to test>`은 테스트하고 싶은 패키지의 이름입니다.

작성한 dts 파일을 타입스크립트 컴파일러로 돌려보기 위해 테스트 스크립트 내부적으로 [dtslint](https://github.com/Microsoft/dtslint)를 사용합니다.

Expand Down
Loading

0 comments on commit eee07ad

Please sign in to comment.