【问题标题】:Using Rewire with TypeScript将 Rewire 与 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 编写的。

标签: unit-testing typescript react-native


【解决方案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 的推荐方法?
  • 完全一样 - 只需模拟生成的文件名并包装导出。我会用一个完整的例子来扩展答案。
猜你喜欢
  • 2019-06-06
  • 2015-03-09
  • 2012-12-14
  • 2016-08-24
  • 2021-01-20
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多