使用Jest与Typescript时的Transpilation

时间:2018-03-08 14:49:26

标签: typescript jestjs

当我在一个Typescript项目中使用Jest启动我的测试套装时,我遇到了这个编译错误:

  

类型错误:   /PATH/instant.ts:   无法读取未定义的属性“某些”

在我的package.json中,我有这个Jest配置:

"jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/src/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
     "js"
    ],
    "collectCoverage": true,
    "coverageReporters": [
     "json",
     "html"
    ]
  }

Instant.ts:

export class Instant {

    constructor(private id: string,
                private name: string) {
    }

}

并且instant.js:

export class Instant {
    constructor(id, name) {
        this.id = id;
        this.name = name;
    }
}
//# sourceMappingURL=instant.js.map

1 个答案:

答案 0 :(得分:0)

我分享自己的Jest配置,该配置对我有用:

{
    preset: 'react-native',
    rootDir: '..',
    setupFiles: [
        '<rootDir>/configuration/jest.setup.js'
    ],
    moduleFileExtensions: [
        'ts',
        'tsx',
        'js'
    ],
    transform: {
        '^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
        '\\.(ts|tsx)$': 'ts-jest'
    },
    testMatch: [
        '<rootDir>/__tests__/**/?(*.)+(spec|test).ts?(x)'
    ],
    testPathIgnorePatterns: [
        '\\.snap$',
        '<rootDir>/node_modules/'
    ],
    collectCoverageFrom: [
        '<rootDir>/src/**/*.{ts,tsx}'
    ],
    coveragePathIgnorePatterns: [
        '<rootDir>/__tests__/'
    ],
    coverageDirectory: '<rootDir>/jest/coverage',
    coverageReporters: [
        'html',
        'text',
        'text-summary'
    ]
}