[Typescript] Step 7. Tests for Types

Step 7: Tests for Types

The assertion type code need to be tested just as the normal code.

export function isITeam(arg: any): arg is ITeam {
  /**
   * {
  iconUrl: string;
  name: string;
  id: string;
  channels: IChannel[];
}
   */
  return (
    typeof arg.iconUrl === 'string' &&
    typeof arg.name === 'string' &&
    typeof arg.id === 'string' &&
    Array.isArray(arg.channels)
  );
}

export function assertIsTypedArray<T>(
  arg: any,
  check: (val: any) => val is T,
): asserts arg is T[] {
  if (!Array.isArray(arg)) {
    throw new Error(`Not an array: ${JSON.stringify(arg)}`);
  }
  if (arg.some((item) => !check(item))) {
    throw new Error(`Violators found: ${JSON.stringify(arg)}`);
  }
}

 

We will write tests for those types code:

One way to setup tests for types is running scheduled job running everyday to see whether typescript new version released would contains breaking changes.

 

2. Setup dtslint (optional)

Dtslint docs

1. Create a new folder under tests folder called types-dtslint

2. Create a tslint.json file under types-dtslint folder

{
  "extends": "dtslint/dtslint.json",
  "rules": {
    "semicolon": false,
    "indent": [true, "tabs"],
    "no-relative-import-in-test": false
  }
}

3. Create a tsconfig.json file under types-dtslint folder

{
  "compilerOptions": {
    "module": "commonjs",
    "lib": ["es6", "dom"],
    "noImplicitAny": true,
    "noImplicitThis": true,
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "types": [],
    "noEmit": true,
    "forceConsistentCasingInFileNames": true,

    // If the library is an external module (uses `export`), this allows your test file to import "mylib" instead of "./index".
    // If the library is global (cannot be imported via `import` or `require`), leave this out.
    "baseUrl": ".",
    "paths": { "mylib/*": ["../../.dist-types/*"] }
  },
  "include": ["."]
}

4. Under root folder, create tsconfig.types.json file

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": ".dist-types",
    "declaration": true,
    "emitDeclarationOnly": true,
    "noEmit": false  
  },
  "include": ["src"]
}

5. Run tsc -P tsconfig.types.json

Command will generate definiation files.

6. Create index.d.ts file under tests/types-dtslint

// Minimum TypeScript Version: 3.8

It telling what minimum typescript version to test against. And also the sub-sequence release versions.

Then you need to export the types file which you want to test against:

// Minimum TypeScript Version: 3.8
export * from '../../.dist-types/data/teams';
export * from '../../.dist-types/types';

7. Create another file test.ts along with index.d.ts

import { assertIsTypedArray, isITeam, ITeam } from '.';

const team: ITeam = null; // $ExpectError: Type 'null' is not assignable to type 'ITeam'.

console.log(team);

8. Run the test: 

yarn dtslint tests/types-dtslint

Results:

ERROR: 3:7  expect  TypeScript@4.3 compile error: 
Type 'null' is not assignable to type 'ITeam'.

 

As we can see, the result output is not as good as we want, we want somthing like Jest test running, can show us what's wrong, using expect api

 3. Setup tsd (recommended)

TSD Docs

1. Create types-tsd folder under tests folder

2. Create index.test-d.ts file under types-tsd folder

import { ITeam } from '../../src/types';
import { expectAssignable, expectNotAssignable } from 'tsd';

//const team1: ITeam = null;
expectNotAssignable<ITeam>(null);
//const team2: ITeam = { channels: [], name: '', iconUrl: '', id: '' };
expectAssignable<ITeam>({
  channels: [],
  name: '',
  iconUrl: '',
  id: '',
});

3. Create index.d.ts file

export * from '../../.dist-types/data/teams';
export * from '../../.dist-types/types';

4. Run yarn tsd tests/types-tsd

 

PROS: code is much understandable and readable. 

CONS: we cannot test multi typescript versions.

 

posted @   Zhentiw  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-08-30 [React & Debug] Quick way to debug Stateless component
2017-08-30 [D3] Drawing path in D3
2016-08-30 [Redux + Webpack] Hot reloading Redux Reducers with Webpack
点击右上角即可分享
微信分享提示