如何为 Typescript 类型编写负面测试?
How do I write negative tests for Typescript typings?
我已经为 Javascript 项目的 Typescript 类型编写了一些测试用例。
正面测试很简单;只需输入一堆代码,它就会编译。像这样:https://github.com/geon/reselect/blob/d5b46b80a28b08ceebc1f19e4300630a0dea751a/test/typings/should_compile/index.ts
negative 测试有点棘手。有些东西应该 不 编译,但我不能再在同一个文件中进行多个测试,因为只要单个测试用例无效,编译就会失败。所以这行不通:https://github.com/geon/reselect/blob/d5b46b80a28b08ceebc1f19e4300630a0dea751a/test/typings/should_not_compile/index.ts
只有当所有文件都编译失败时,如何确保测试通过?
这些测试应该可以由 Travis CI 运行。 (我没有经验。抱歉。)
正如@wkrueger 所指出的,Dtslint 可以做到这一点!
https://github.com/Microsoft/dtslint#write-tests
只需在任何阴性测试上方添加行 // $ExpectError
。
从 TS 3.9 开始你应该使用
// @ts-expect-error
我已经为 Javascript 项目的 Typescript 类型编写了一些测试用例。
正面测试很简单;只需输入一堆代码,它就会编译。像这样:https://github.com/geon/reselect/blob/d5b46b80a28b08ceebc1f19e4300630a0dea751a/test/typings/should_compile/index.ts
negative 测试有点棘手。有些东西应该 不 编译,但我不能再在同一个文件中进行多个测试,因为只要单个测试用例无效,编译就会失败。所以这行不通:https://github.com/geon/reselect/blob/d5b46b80a28b08ceebc1f19e4300630a0dea751a/test/typings/should_not_compile/index.ts
只有当所有文件都编译失败时,如何确保测试通过?
这些测试应该可以由 Travis CI 运行。 (我没有经验。抱歉。)
正如@wkrueger 所指出的,Dtslint 可以做到这一点!
https://github.com/Microsoft/dtslint#write-tests
只需在任何阴性测试上方添加行 // $ExpectError
。
从 TS 3.9 开始你应该使用
// @ts-expect-error