简体   繁体   English

将 TypeScript 与 Jest 一起使用不会捕获语法错误

[英]Using TypeScript with Jest not catching syntax errors

When compiling typescript back to js, you can specify the option --alwaysStrict which:将打字稿编译回 js 时,您可以指定选项--alwaysStrict ,其中:

Parse in strict mode and emit "use strict" for each source file以严格模式解析并为每个源文件发出“使用严格”

So, if you are missing a compulsory parameter in a function, it gets caught by this strict mode.因此,如果您在函数中缺少一个强制参数,它就会被这种严格模式捕获。

We are using ts-jest so we can use Jest to test our Typescript code.我们正在使用ts-jest因此我们可以使用 Jest 来测试我们的 Typescript 代码。 The problem we face is that we have not found a way to mimic the strict parsing behaviour.我们面临的问题是我们还没有找到模仿严格解析行为的方法。

This is really annoying because all the test seem to pass, but from time to time there is a syntactic mistake that slips through the cracks and we only notice when we are creating the production build (where we set the --alwaysStrict )这真的很烦人,因为所有测试似乎都通过了,但有时会出现语法错误,我们只在创建生产版本时才注意到(我们设置了--alwaysStrict

In our jest.config.js we have:在我们的jest.config.js我们有:

module.exports = {
  roots: ["<rootDir>/src"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  "testEnvironment": "node"
};```

ts-jest uses the tsconfig.json from your project by default. ts-jest默认使用项目中的tsconfig.json

(Note: if you want a separate config file for your tests you can configure ts-jest to use a different config file ) (注意:如果你想要一个单独的测试配置文件,你可以配置ts-jest以使用不同的配置文件

You can set alwaysStrict in the compilerOptions section ofthe config file and ts-jest use that flag when compiling your TypeScript.您可以在配置文件compilerOptions部分中设置alwaysStrict ,并且ts-jest在编译您的 TypeScript 时使用该标志。

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

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