我正在使用TypeScript处理React-Native项目。要编写我的单元测试,我想使用babel-plugin-rewire来模拟我的模块导入。但是,在从ES6转换为ES5时,TypeScript会在导入结尾处添加_1
后缀,这会破坏我的测试代码。
请考虑以下事项:
import Test from 'test-file';
这可能会被TypeScript转换为:
var test_file_1 = require('test-file');
要使用Rewire插件模拟Test类,我必须写:
ComponentToTest.__Rewire__('Test', TestMock);
但由于导入已重命名,因此会中断。
虽然这是by design,但我很想知道是否有任何解决方法。
感谢。
答案 0 :(得分:7)
我不了解Babel-Plugin-Rewire,但如果您单独使用TypeScript和Rewire,包括将ES6模块编译到ES5,您可以轻松地直接模拟生成的文件导入。
即。这应该有效:
ComponentToTest.__set__('test_file_1', { default: TestMock });
那取决于_1后缀,后者可能会在以后的TypeScript版本中发生变化,或者您对TypeScript代码本身进行了某些更改。我认为这风险相当低。
Full Rewire + TS示例:
Component.ts:
import DefaultComponent from "other-component";
import { IndividuallyExportedComponent } from "yet-another-component";
// ... Do something worth testing
组件的Test.ts:
import rewire = require("rewire");
let RewiredComponent = rewire("../src/Component");
let defaultMock = { /* 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.