在 TypeScript 中使用 Rewire [英] Using Rewire with TypeScript

查看:87
本文介绍了在 TypeScript 中使用 Rewire的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a React-Native project using TypeScript. To write my unit tests I would like to use the babel-plugin-rewire to mock my module imports. However, TypeScript adds a _1 suffix at the end of imports while converting from ES6 to ES5, and this breaks my test code.

考虑以下事项:

import Test from 'test-file';

这可能会被 TypeScript 转换为:

this might be converted by TypeScript to:

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

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

To mock the Test class using the Rewire plugin I would have to write:

ComponentToTest.__Rewire__('Test', TestMock);

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

but since the import has been renamed this will break.

虽然这是设计,但我很想知道是否有任何解决方法.

Though this is by design, I would love to know if there are any workarounds.

谢谢.

推荐答案

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

I don't know about Babel-Plugin-Rewire but if you use TypeScript with Rewire alone, including compiling ES6 modules to ES5, you can easily mock the generated file import directly.

即这应该有效:

ComponentToTest.__set__('test_file_1', { default: TestMock });

这取决于 _1 后缀,它可能会在以后的 TypeScript 版本中发生变化,或者如果您对 TypeScript 代码本身进行某些更改.不过我认为风险相当低.

That does then depends on the _1 suffix, which could plausibly change in later TypeScript releases or if you make certain changes to the TypeScript code itself. I think that's fairly low risk though.

完全重新布线 + TS 示例:

Component.ts:

Component.ts:

import DefaultComponent from "other-component";
import { IndividuallyExportedComponent } from "yet-another-component";

// ... Do something worth testing

组件-Test.ts:

Component-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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆