【问题标题】:Jest will not process import statement in typescriptJest 不会处理打字稿中的导入语句
【发布时间】:2019-11-29 14:19:24
【问题描述】:

我正在尝试运行基本测试。

我的源代码在 src/index.ts 中,代码如下:

    const sum = (a, b) => {return a+b}

    export default sum

我的测试在 tests/index.test.ts 中,代码如下:

    import sum from "./index";

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3)
})

并且在运行 npm run test 时 package.json 设置为 test:"jest" 给我这个错误:

 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import sum from "./index";
                                                                                                    ^^^

    SyntaxError: Unexpected identifier

【问题讨论】:

    标签: node.js typescript jestjs


    【解决方案1】:

    您应该确保使用ts-jest。

    ts-jest 是一个 TypeScript 预处理器,它支持 Jest 的源映射,让您可以使用 Jest 测试用 TypeScript 编写的项目。

    在你的项目根目录下创建一个jest.config.js文件并添加这个配置:

    module.exports = {
      preset: 'ts-jest/presets/js-with-ts'
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 2021-05-15
      • 2018-04-26
      • 2016-02-26
      • 2021-01-08
      相关资源
      最近更新 更多