我从angular.io开始学习本教程

正如他们所说,我已经创建了hero.spec.ts文件来创建单元测试:

import { Hero } from './hero';
describe('Hero', () => {
  it('has name', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.name).toEqual('Super Cat');
  });
  it('has id', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.id).toEqual(1);
  });
});

单元测试工作起来很有魅力。问题是:我看到了一些错误,在教程中提到过:

我们的编辑和编译器可能会抱怨他们不知道它是什么 和期望,因为他们缺乏打字文件描述 茉莉花。我们可以暂时忽略那些恼人的抱怨 无害的。

他们确实忽略了这一点。尽管这些错误是无害的,但当我收到一堆错误时,在输出控制台中看起来并不好。

我得到的例子是:

无法找到名称“describe”。 找不到名字“it”。 找不到名称“expect”。

我能做些什么来弥补呢?


当前回答

为了让TypeScript编译器在编译过程中使用所有可见的类型定义,types选项应该完全从tsconfig中的compilerOptions字段中删除。json文件。

当compilerOptions字段中存在一些类型条目时,这个问题就会出现,而与此同时,笑话条目却缺失了。

所以为了解决这个问题,在你的tsconfig中输入compilerOptions字段。Json应该在类型区域中包含jest,或者完全摆脱类型:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "types": ["reflect-metadata", "jest"],  //<--  add jest or remove completely
    "moduleResolution": "node",
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

其他回答

我希望你已经安装了

npm install --save-dev @types/jasmine

然后把下面的导入放在hero.spec.ts文件的顶部

import 'jasmine';

这应该能解决问题。

使用Typescript@2.0或更高版本,您可以安装类型:

npm install -D @types/jasmine

然后使用tsconfig.json中的types选项自动导入类型:

"types": ["jasmine"],

这个解决方案不需要import {} from 'jasmine';在每个规范文件中。

只需要做以下事情来在Lerna Mono-repo中获取@types 其中存在几个node_module。

npm install -D @types/jasmine

然后在每个tsconfig中。每个模块或应用程序的文件

"typeRoots": [
  "node_modules/@types",
  "../../node_modules/@types" <-- I added this line
],

为了让TypeScript编译器在编译过程中使用所有可见的类型定义,types选项应该完全从tsconfig中的compilerOptions字段中删除。json文件。

当compilerOptions字段中存在一些类型条目时,这个问题就会出现,而与此同时,笑话条目却缺失了。

所以为了解决这个问题,在你的tsconfig中输入compilerOptions字段。Json应该在类型区域中包含jest,或者完全摆脱类型:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "types": ["reflect-metadata", "jest"],  //<--  add jest or remove completely
    "moduleResolution": "node",
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

看看导入,也许你有一个循环依赖,这是我的错误,使用import {} from 'jasmine';将修复控制台中的错误并使代码可编译,但不删除devil的根(在我的情况下是周期依赖)。