我正在使用 TypeScript 开发一个 React-Native 项目。为了编写我的单元测试,我想使用babel-插件-重新布线 https://github.com/speedskater/babel-plugin-rewire模拟我的模块导入。然而,TypeScript 添加了一个_1
从 ES6 转换为 ES5 时,在导入末尾添加后缀,这会破坏我的测试代码。
考虑以下:
import Test from 'test-file';
这可能会被 TypeScript 转换为:
var test_file_1 = require('test-file');
要使用 Rewire 插件模拟 Test 类,我必须编写:
ComponentToTest.__Rewire__('Test', TestMock);
但由于导入已被重命名,这将被破坏。
虽然这是按设计 https://github.com/Microsoft/TypeScript/issues/6264,我很想知道是否有任何解决方法。
Thanks.
我不知道 Babel-Plugin-Rewire,但如果你单独使用 TypeScript 和 Rewire,包括将 ES6 模块编译为 ES5,你可以轻松地直接模拟生成的文件导入。
IE。这应该有效:
ComponentToTest.__set__('test_file_1', { default: TestMock });
这确实取决于 _1 后缀,在以后的 TypeScript 版本中或者如果您对 TypeScript 代码本身进行某些更改,该后缀可能会发生变化。我认为这风险相当低。
完整重新接线 + TS 示例:
组件.ts:
import DefaultComponent from "other-component";
import { IndividuallyExportedComponent } from "yet-another-component";
// ... Do something worth testing
组件测试.ts:
import rewire = require("rewire");
let RewiredComponent = rewire("../src/Component");
let defaultComponentMock = { /* Make a mock of your dependency */ };
RewiredComponent.__set__('other_component_1', {
default: defaultComponentMock
});
let individuallyExportedMock = { /* Make a mock of your dependency */ };
RewiredComponent.__set__('yet_another_component_1', {
IndividuallyExportedComponent: individuallyExportedMock
});
// RewiredComponent has the wrong type now. YMMV, but I'm doing type-wrangling
// that looks something like:
import * as RealComponent from "../src/Component";
let Component: typeof RealComponent & typeof RewiredComponent = <any> RewiredComponent;
// 'Component' now has the same type as the real module, plus the
// .__set__ etc methods from Rewire.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)