将 Rewire 与 TypeScript 一起使用

Posted

技术标签:

【中文标题】将 Rewire 与 TypeScript 一起使用【英文标题】:Using Rewire with TypeScript 【发布时间】:2017-02-19 23:29:40 【问题描述】:

我正在使用 TypeScript 开发一个 React-Native 项目。要编写我的单元测试,我想使用 babel-plugin-rewire 来模拟我的模块导入。但是,TypeScript 在从 ES6 转换为 ES5 时在导入末尾添加了 _1 后缀,这破坏了我的测试代码。

考虑以下几点:

import Test from 'test-file';

这可能会被 TypeScript 转换为:

var test_file_1 = require('test-file');

要使用 Rewire 插件模拟 Test 类,我必须编写:

ComponentToTest.__Rewire__('Test', TestMock);

但由于导入已重命名,这将中断。

虽然这是by design,但我很想知道是否有任何解决方法。

谢谢。

【问题讨论】:

您是如何设法将测试模块导入规范文件(即import SomeClass, __Rewire__ from '../src/SomeClass';)的?当我尝试运行测试时,编译器会打印以下错误"SomeClass" has no exported member '__Rewire__'。附言spec 文件也是用 TypeScript 编写的。 【参考方案1】:

我不知道 Babel-Plugin-Rewire 但是如果你单独使用 TypeScript 和 Rewire,包括将 ES6 模块编译为 ES5,你可以轻松地直接模拟生成的文件导入。

即这应该有效:

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

组件-Test.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.

【讨论】:

你能不能提一下单独使用 TypeScript 和 Rewire 的推荐方法? 完全一样 - 只需模拟生成的文件名并包装导出。我会用一个完整的例子来扩展答案。

以上是关于将 Rewire 与 TypeScript 一起使用的主要内容,如果未能解决你的问题,请参考以下文章

将 Typescript 与 Laravel 和 Vue.js 一起使用,导入不使其成为 Vue 组件?

如何使 typescript 与 Promise 一起使用?

将 Typescript 2 @Types 与 typescript 1.8.10 一起使用

如何使 Next.js getStaticProps 与打字稿一起使用

将 typescript 与 Babel 7 Standalone 一起使用

将 Nodejs 与 Typescript 一起使用