单元测试 – 使用Rewire和TypeScript

前端之家收集整理的这篇文章主要介绍了单元测试 – 使用Rewire和TypeScript前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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.
原文链接:https://www.f2er.com/react/300866.html

猜你在找的React相关文章