首页 > 解决方案 > 使用 create-react-app 通过 JEST 运行测试时不显示 TypeScript 错误

问题描述

正如标题所说,在使用create-react-app设置的项目中编写不正确的 TypeScript 代码时,通过. 也许这是预期的行为?然而,如果能得到错误以防止在测试中编写不正确的 TypeScript 也会很好npm test

错误代码示例:

// App.test.tsx
it('Test of incorrect TypeScript', () => {
  let aSimpleString: string = 'hello';
  aSimpleString = 5;
});

PS 如果您想知道我正在使用 typeScript 版本的 create-react-app ,请通过:npx create-react-app my-app --typescript. 其他一切正常,如果我在组件文件中编写了不正确的 TypeScript,终端会让我知道

标签: javascriptreactjstypescriptjestjscreate-react-app

解决方案


测试不做类型检查。测试也不需要正确编译,虽然我不确定为什么会这样,所以测试中的类型错误不会出现。

如果要对测试进行类型检查,请使用yarn tsc默认配置。这将执行类型检查,并且它已noEmit设置,因此它不会构建任何东西。测试文件默认包含在配置中。

如果您愿意,您还可以将测试脚本更新为:tsc && react-scripts test.

请注意,这只会进行类型检查。您还可以使用 eslint 进行 linting,例如

tsc && eslint --ext ts,tsx,js src && react-scripts test

推荐阅读