用 Jest 测试 Typescript 接口

Testing Typescript Interface with Jest

下面是我的界面和测试文件。当我 运行 开玩笑地针对它进行代码覆盖率测试时,它一直说第 1 行和第 2 行未被测试覆盖。接口的代码覆盖甚至是可能的吗?或者我应该从覆盖率报告中排除任何接口?

index.tsx

export interface StoreState {
    languageName: string;
    enthusiasmLevel: number;
}


index.test.tsx

import { StoreState } from '../types';

it('has a languageName of "TypeScript"', () => {
    const state: StoreState = { languageName: 'TypeScript', enthusiasmLevel: 3 };
    expect(state.languageName).toEqual('TypeScript');
});

it('has an enthusiasm level of 3', () => {
  const state: StoreState = { languageName: 'TypeScript', enthusiasmLevel: 3 };
  expect(state.enthusiasmLevel).toEqual(3);
});

这是 ts-jest (Issue #378) 的一个已知问题。项目所有者目前建议从 Jest 覆盖范围中排除接口文件:

kulshekhar 2018 年 1 月 1 日评论:

I don't think there's anything that can be done in ts-jest to fix this. I've taken a closer look at this issue and there are two ways to get the desired outcome:

  • exclude files that contain only types from coverage
  • add and export a dummy function/variable from a file that contains only types

When TypeScript transpiles files, it doesn't convert 'pure type' imports to require statements. This results in Jest not picking and passing those files to ts-jest.

GeeWee 2018 年 1 月 2 日评论:

I don't think we can exclude files that contain only types. I also think this is a wontfix unless jest adds the capabillity for transformers to opt files out of coverage or something akin to that.

例如,您可以使用 coveragePathIgnorePatterns 根据仅包含类型的文件的命名约定排除文件(例如,I 前缀后跟大写字母,例如“ISerializable"):

{
  "jest": {
    ...
    "coveragePathIgnorePatterns": [
      "**/I[A-Z]*.{ts}"
    ]
  }
}