使用Typescript模拟Jest中的类时引发“缺少分号”错误

ccgok5k5  于 2023-09-28  发布在  Jest
关注(0)|答案(2)|浏览(168)

我正在使用Typescript并试图用Jest测试我的代码,我对一个类进行了类型转换,这样我就可以模拟它。
不幸的是,当我运行测试套件时,我得到了以下错误:

  1. SyntaxError: C:\Projects\sim_editor\server\src\tests\routes.test.ts: Missing semicolon (7:37)

下面是我的代码:

  1. describe('Unit test api routes', () => {
  2. jest.mock('../controllers')
  3. const mkControllers = Controllers as jest.MockedClass<typeof Controllers>
  4. beforeEach(() => {
  5. mkControllers.mockClear()
  6. })
  7. .
  8. .
  9. .
  10. The rest of my test suite
  11. })

错误是指我声明“mkControllers”的那一行。
下面是错误的更深层次的日志:

  1. at Parser._raise (node_modules/@babel/parser/src/parser/error.js:97:45)
  2. at Parser.raiseWithData (node_modules/@babel/parser/src/parser/error.js:92:17)
  3. at Parser.raise (node_modules/@babel/parser/src/parser/error.js:41:17)
  4. at Parser.semicolon (node_modules/@babel/parser/src/parser/util.js:131:10)
  5. at Parser.parseVarStatement (node_modules/@babel/parser/src/parser/statement.js:707:10)
  6. at Parser.parseStatementContent (node_modules/@babel/parser/src/parser/statement.js:223:21)
  7. at Parser.parseStatement (node_modules/@babel/parser/src/parser/statement.js:163:17)
  8. at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/parser/src/parser/statement.js:880:25)
  9. at Parser.parseBlockBody (node_modules/@babel/parser/src/parser/statement.js:856:10)
  10. at Parser.parseBlock (node_modules/@babel/parser/src/parser/statement.js:826:10)

谢谢.

cld4siwp

cld4siwp1#

显然,我没有配置Babel来使用Typescript,因为Jest必须使用它。请确保您遵循“使用Babel”和“使用Typescript”下的说明here

xzlaal3s

xzlaal3s2#

Jest通过Babel支持TypeScript。按照以下步骤进行配置。
第1步:通过在控制台中粘贴此命令来添加依赖项。

  1. npm install --save-dev babel-jest @babel/core @babel/preset-env @babel/preset-typescript

步骤2:在项目的根目录下创建一个名为babel.config.js的新文件。
步骤3:将此文本粘贴到babel.config.js文件中。

  1. module.exports = {
  2. presets: [
  3. ['@babel/preset-env', {targets: {node: 'current'}}],
  4. '@babel/preset-typescript',
  5. ],
  6. };

相关问题