Jest无法导入ts / tsx模块

时间:2019-05-30 22:19:34

标签: reactjs typescript gruntjs jestjs ts-jest

当我尝试将打字稿模块导入单元测试时,出现错误,提示Unable to resolve path to module 'src/js/TestNum'。从js / jsx文件执行相同的导入没有相同的问题。

过去,在导入打字稿模块时遇到问题,它抱怨出现意外的令牌语法错误。

TestNum.ts

export const TestNum1 = 5;
export const TestNum2 = 10;

TestStr.js

export const TestStr1 = '5';
export const TestStr2 = '10';

test.js

/* global describe test */
import expect from 'expect';
import { TestNum1 } from 'src/js/TestNum';
import { TestStr1 } from 'src/js/TestStr';

describe('example', () => {
  test('if constant is 5', () => {
    expect(TestNum1).toEqual(5);
  });
  test('if constant is "5"', () => {
    expect(TestStr1).toEqual(5);
  });
});

在vscode中,如果我单击失败的导入并按F2键,它将导航到该导入的定义。

package.json

{
  "devDependencies": {
    "@types/react": "^16.8.18",
    "@types/react-dom": "^16.8.4",
    "babel-jest": "^24.8.0",
    "babel-plugin-graphql-tag": "1.6.0",
    "child_process": "^1.0.2",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.13.1",
    "expect": "^24.8.0",
    "grunt": "0.4.5",
    "grunt-exec": "^3.0.0",
    "jest": "^23.4.1",
    "jest-config": "^24.8.0",
    "jest-html-reporter": "^2.5.0",
    "load-grunt-config": "^1.0.2",
    "react-test-renderer": "^16.8.6",
    "sinon": "^7.3.2",
    "ts-jest": "23.10.5",
    "typescript": "^3.4.5"
  },
  "scripts": {
    "start": "start-dev-shell",
    "stop": "stop-dev-shell",
    "restart": "restart-dev-shell"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  }
}

jest.config.js

const { defaults } = require('jest-config');

module.exports = {
  coverageDirectory: 'build/test-results/code-coverage-reports',
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx', 'js', 'jsx'],
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/__mocks__/fileMock.js',
    '\\.(css|less|scss)$': '<rootDir>/__mocks__/styleMock.js'
  },
  'reporters': ['default', ['./node_modules/jest-html-reporter', { 'pageTitle': 'Test Report' }]],
  setupFiles: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: [
    '<rootDir>/node_modules/',
    '<rootDir>/build-utils/',
    '<rootDir>/dist/',
    '<rootDir>/build/',
    '<rootDir>/__mocks__/'
  ],
  testRegex: 'test/unit/.+Tests?\\.(js|ts|jsx|tsx)?', //updated to grab ts/tsx tests
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.tsx?$': 'ts-jest'
  },
  modulePaths: ['<rootDir>']
};

修改

根据这些评论,我发现一个新发现是,如果我将测试切换为打字稿测试,那么如果从src而不是相对路径中进行引用,它将找不到我的模块。 ../../src。这也将阻止IDE跳转到定义。

0 个答案:

没有答案