注意:我的目标是为项目带来类似Rewire的功能。无论是使用 Rewire 包、babel-plugin-rewire 还是任何其他满足我目标的库。考虑到这一点,这里是细节:
我正在尝试使用 Mocha 和 Chai 设置一个新的 Typescript 项目。其中一个单元测试要求我使用rewire
,它不适用于 ES6 导入。所以,我最终使用babel-plugin-rewire
. 但是,我无法让它工作。例如,以下行:
const jwtVerify = hello.__get__("hello");
失败TypeError: _get__(...).__get__ is not a function
。
我在这里设置了一个简约的可复制公共 repo:https ://github.com/naishe/typescript-babel如果你想玩它。
这是最小的项目设置:
src/hello.ts
export default function(name: string) {
return `Hello ${name}`;
}
function privateHello(name: string) {
return `Not exported Hello ${name}`;
}
测试/index.spec.ts
import hello from "../src/hello";
import { expect } from "chai";
describe("Typescript + Babel usage suite", () => {
// This works!
it("should return string correctly", () => {
expect(hello("mocha")).to.be.equal("Hello mocha");
});
// These fail
it("should check if jwtVerify function exists", () => {
//@ts-ignore
const jwtVerify = hello.__get__("hello");
expect(jwtVerify).to.be.a("function");
});
it("should check if private function exists", () => {
//@ts-ignore
const privateHello = hello.__get__("privateHello");
expect(privateHello).to.be.a("function");
});
});
测试/babel-register.js
const register = require('@babel/register').default;
register({ extensions: ['.ts', '.tsx', '.js', '.jsx'] });
babelrc.json
{
"plugins": ["rewire"]
}
babel.config.js
module.exports = (api) => {
// Cache configuration is a required option
api.cache(false);
const presets = [
"@babel/preset-typescript",
"@babel/preset-env"
];
return { presets };
};
mocharc.json
{
"extension": ["ts"],
"spec": "test/**/*.spec.ts",
"require": "test/babel-register.js"
}
package.json 的相关部分
"scripts": {
"test": "mocha"
},
"devDependencies": {
"@babel/cli": "^7.12.10",
"@babel/core": "^7.12.10",
"@babel/preset-env": "^7.12.11",
"@babel/preset-typescript": "^7.12.7",
"@babel/register": "^7.12.10",
"@types/chai": "^4.2.14",
"@types/mocha": "^8.2.0",
"@typescript-eslint/eslint-plugin": "^4.13.0",
"@typescript-eslint/parser": "^4.13.0",
"chai": "^4.2.0",
"eslint": "^7.17.0",
"mocha": "^8.2.1",
"ts-node": "^9.1.1",
"typescript": "^4.1.3"
},
"dependencies": {
"babel-core": "^6.26.3",
"babel-plugin-rewire": "^1.2.0"
}
npm test
发出这个:
Typescript + Babel usage suite
✓ should return string correctly
1) should check if jwtVerify function exists
1 passing (4ms)
1 failing
1) Typescript + Babel usage suite
should check if jwtVerify function exists:
TypeError: _get__(...).__get__ is not a function
at Context.<anonymous> (test/index.spec.ts:10:29)
at processImmediate (internal/timers.js:456:21)
我已经对 babel-plugin-rewire提出了担忧,但它似乎非常沉默。所以,我想知道是否还有其他方法可以实现这一目标?