[英]How do I correctly configure mocha tests with ts_transformer_keys?
我似乎无法使用我的 mocha 测试为 ts-transform-keys 设置自定义转换器。
我正在使用摩卡 6.1.4
ts-node 8.3.0 https://www.npmjs.com/package/ts-node
ts-trasnformer-keys 0.3.5 https://github.com/kimamula/ts-transformer-keys
ttypescript 1.5.7 https://github.com/cevek/ttypescript
ts-node 文档说您不能在 CLI 上设置自定义转换器,只能以编程方式。 所以我正在尝试使用 ttypescript 来绕过这个限制。
我试过以下...
注意:test.ts 包含以下内容
import { keys } from 'ts-transformer-keys';
describe("xyz"), () => {
it("123", (done) => {
keys<CustomInterface>();
});
});
尝试 1) - 使用环境变量设置 ts-node
TS_NODE_COMPILER="ttypescript" mocha test/test.ts --require ts-node/register
然后我在 test/tsconfig.json 中有以下内容
{
"compilerOptions": {
"plugins": [
{ "transform": "ts-transformer-keys/transformer" }
]
}
}
这会导致Uncaught TypeError: ts_transformer_keys_1.keys is not a function
这表明在编译时未使用自定义转换器。
尝试 2) 遵循来自 ts-transformer-keys 的 typescript API 示例
我添加了一个 mocha.opts 文件,其中包含以下内容
--file test/transformer-config.js
和一个带有以下内容的 transformer-config.js 文件
const ts = require('typescript');
const keysTransformer = require('ts-transformer-keys/transformer').default;
const program = ts.createProgram(['test/test.ts'], {
strict: true,
noEmitOnError: true,
target: ts.ScriptTarget.ES5
});
const transformers = {
before: [keysTransformer(program)],
after: []
};
const { emitSkipped, diagnostics } = program.emit(undefined, undefined, undefined, false, transformers);
if (emitSkipped) {
throw new Error(diagnostics.map(diagnostic => diagnostic.messageText).join('\n'));
}
然后我像这样调用它mocha test/test.ts --require ts-node/register
这会导致以下错误
/Users/jjohnson/Documents/OCS/hmp/git/hmp-server/server/test/ttypescript-register.js:17
throw new Error(diagnostics.map(diagnostic => diagnostic.messageText).join('\n'));
^
Error: [object Object]
[object Object]
[object Object]
at Object.<anonymous> (/Users/jjohnson/Documents/OCS/hmp/git/hmp-server/server/test/ttypescript-register.js:17:9)
at Module._compile (internal/modules/cjs/loader.js:777:30)
...
感觉就像在尝试 1 中,它从来没有调用在 tsconfig.json 中设置自定义转换器的代码,或者如果它被调用,代码会默默地失败。
感觉就像在尝试 2 中我正在创建 typescript 程序的新实例,然后由于某种原因失败了。 即使它成功了,我也不确定这是否是 go 关于配置事物的正确方法,因为 ts.createProgram 想要一个它将转换的文件的 RootNames 列表。
也许我的整个方法都是错误的。
我真正想要的是一种方法,在我的 mocha 测试中,我可以验证预期的结果类型是方法返回的内容。 而且我希望能够在不接触太多源代码的情况下做到这一点。
您应该能够定义所需的模块(见下文)并以编程方式运行 ts-node。 这样,您可以安全地使用任何客户变压器。
// tsnode.js
const transformer = require('ts-transformer-keys/transformer').default;
require("ts-node").register({
transformers: program => ({
before: [
transformer(program)
]
})
});
然后你可以用 require 运行 mocha
mocha --require './tsnode.js' --watch-extensions ts,tsx "test/**/*.{ts,tsx}
您可以告诉ts-node
在tsconfig.json
中使用哪个编译器。 这在ts-node
文档中有所介绍。 如果您使用转换器大概也使用ttypescript
编译器。 你只需要添加这个:
"ts-node": {
"compiler": "ttypescript"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.