加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

单元测试 – 使用Rewire和TypeScript

发布时间:2020-12-15 20:45:09 所属栏目:百科 来源:网络整理
导读:我正在使用TypeScript处理React-Native项目.要编写我的单元测试,我想使用 babel-plugin-rewire来模拟我的模块导入.但是,在从ES6转换为ES5时,TypeScript会在导入结尾处添加_1后缀,这会破坏我的测试代码. 考虑以下: import Test from 'test-file'; 这可能会被
我正在使用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,但我很想知道是否有任何解决方法.

谢谢.

我不知道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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读