当我尝试将打字稿模块导入我的单元测试时,我收到一条错误消息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';
测试.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,它将导航到导入的定义。
包.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 跳转到定义。