unit-testing - 将 Rewire 与 TypeScript 结合使用

标签 unit-testing typescript react-native

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

考虑以下几点:

import Test from 'test-file';

这可能会被 TypeScript 转换为:

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

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

ComponentToTest.__Rewire__('Test', TestMock);

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

尽管这是 by design ,我很想知道是否有任何解决方法。

谢谢。

最佳答案

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

即这应该有效:

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

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

完整的 Rewire + TS 示例:

组件.ts:

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

// ... Do something worth testing

组件测试.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.

关于unit-testing - 将 Rewire 与 TypeScript 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39976975/

相关文章:

javascript - 如何声明 useState() 初始值为 null,然后再给它一个对象值?

mysql - Sequelize 实例的构建似乎花费了太长时间

reactjs - 使用 redux-persist 保存和检索状态 - React Native

java - Spring JUnit Mockito 单元测试 Controller 指定的类是一个接口(interface)

javascript - 在 Mongoose 中,如何根据相关集合中的值查找记录?

javascript - 如何在react-native(web/android/ios)中的图像上创建链接?

javascript - 如何添加新 key :value pair to an already existing array state variable react native

java - 在单元测试中使用反射来测试注释的存在是否被认为是好的做法?

java - groovy soapUI反序列化

unit-testing - 这是否遵循 AAA 模式?