简体   繁体   English

ts-jest:忽略 TypeScript 类型错误

[英]ts-jest: TypeScript type errors are ignored

I just started learning TypeScript and tried some simple app with jest unit test (using ts-jest):我刚开始学习 TypeScript,并尝试了一些带有 jest 单元测试的简单应用程序(使用 ts-jest):

simple app.ts module:简单的 app.ts 模块:

function greet(person: string): string {
  return `Hello, ${person}`;
}

exports.greet = greet;

simple app.spec.ts code:简单的 app.spec.ts 代码:

const greetObject = require('../app');

greetObject.greet(1);

describe('greet function', () => {
  it('should return greeting', () => {
    expect(greetObject.greet('Dude')).toEqual('Hello, Dude');
  });
  it('should throw type exception', () => {
    const spy = jest.spyOn(greetObject, 'greet');
    greetObject.greet(1);
    /** @todo what should happen ? */
  });
});

and the question is: should I receive type error or not ?问题是:我是否应该收到类型错误? In fact, I do not receive any errors here.事实上,我在这里没有收到任何错误。

But if I call greet with wrong parameter type in app.ts file the whole test suite is failing.但是如果我在 app.ts 文件中使用错误的参数类型调用greet,整个测试套件就会失败。

Am I missing something in TypeScript unit testing ?我在 TypeScript 单元测试中遗漏了什么吗?

UPD.更新。 Converted require to ES6 import.将 require 转换为 ES6 导入。 TypeScript diagnostics are now working, but I still don't know if I can do anything with wrong types and test those situations. TypeScript 诊断现在正在工作,但我仍然不知道我是否可以对错误的类型做任何事情并测试这些情况。 Any advice is appreciated.任何建议表示赞赏。

should I receive type error or not ?我应该收到类型错误吗?

Not here.不在这里。

What you are testing is the JS output of your TS file.您正在测试的是 TS 文件的 JS 输出。

TS errors are compilation time errors. TS 错误是编译时错误。

I still don't know if I can do anything with wrong types and test those situations.我仍然不知道我是否可以对错误的类型做任何事情并测试这些情况。

There is no type checking at runtime with TypeScript, since the runtime is not TypeScript, but JavaScript. TypeScript 在运行时没有类型检查,因为运行时不是TypeScript,而是 JavaScript。

If you want to validate some object received, you should implement actual checking functions.如果您想验证接收到的某个对象,您应该实现实际的检查功能。

maybe helpful :也许有帮助:

How to check the object type on runtime in TypeScript? 如何在 TypeScript 中检查运行时的对象类型?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM