我正在尝试使用Intern设置一个Node.js + TypeScript项目进行测试。当我使用"commonjs"编译项目时,一切正常(我为正常构建这样做);而 TypeScript 在编译 "amd" 时同样高兴,这是 Intern 所要求的。但是,当通过测试时intern-client
,它会抱怨几件事:
首先,从"index.ts"文件(所谓的"桶"模块)导入是行不通的。我的设置是这样的(所有内容都在同一个目录中):
// index.ts
export { x } from './x'
// x.ts
export function x() {}
// x.test.ts
import { x } from '.' // "Error: Failed to load module ..."
事实上,生成的JavaScript代码(用于x.test.ts
)看起来像这样:
define(["require", "exports", "."], function (...) { ... })
而且我不确定AMD是否知道如何处理"."
。
第二个问题发生在同样的情况下(TypeScript 编译得很愉快,但intern-client
抱怨)。总之,我在执行以下操作时出现错误:
import jsdom = require('jsdom')
我需要将其转换为:
const jsdom = require('jsdom')
让实习生能够处理它。
这是我用来编译测试tsconfig.json
文件:
{
"compilerOptions": {
"target": "es6",
"module": "amd",
"moduleResolution": "node",
"sourceMap": true,
"rootDir": "src",
"outDir": "build/tests",
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
这是我的intern.js
配置文件,以防万一:
define({
suites: ['build/tests/**/*.test.js'],
excludeInstrumentation: true,
filterErrorStack: true
})
编辑(2017-05-03)
为了帮助理解这个问题,以下是该项目目录树的摘录:
build
tests // The compiled tests will end up here
src
core
utils
x.ts
x.test.ts
// Other files, each containing a function that I would like to unit-test...
intern.js
package.json
tsconfig.json
...
关于第一个问题,AMD 对像 '." 这样的导入的处理方式与 Node 不同。虽然它们都将"."映射到软件包,但 Node 使用默认模块名称index.js
,而 AMD 使用main.js
。要使事情在 AMD 加载器中正常工作,您需要首先为"."定义一个包,然后告诉 AMD 加载器用于该包的默认模块。根据您的项目布局,您可以像这样配置实习生:
loaderOptions: {
map: {
// When a module in src/ references 'src/utils', redirect
// it to 'utils'
'src': {
'src/utils': 'utils'
}
},
packages: [
// Define a package 'utils' with files in 'src/utils' that defaults
// to the module index.js
{ name: 'utils', location: 'src/utils', main: 'index.js' }
]
}
关于第二个问题,目前尚不清楚问题到底是什么。导入语句将被 TypeScript 转换为define
依赖项,因此 Intern 永远不会看到它们。