javascript - 导出一个函数只是为了测试被认为是一种不好的做法吗?

标签 javascript node.js reactjs testing design-patterns

我有这个问题,尤其是在阅读了关于测试 React 组件的官方 redux 文档之后:

https://github.com/reduxjs/redux/blob/master/docs/recipes/WritingTests.md

In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component

连大名鼎鼎https://www.reactboilerplate.com/导出命名的未连接组件只是为了能够在不模拟商店的情况下测试它们。

但是导出一些东西只是为了让事情更容易测试不是很糟糕吗?

在某些情况下,开发人员可能会因为从一个文件中导出了两个内容而进行了错误的导入并引入了错误。

所以,问题本质上是:

我们可以更改实际代码以使测试更容易吗?

虽然这个问题是 React 特有的,但如果知道其他语言或框架是否有类似的问题以及如何处理这些问题,我们会很高兴。

最佳答案

您始终可以根据您的环境进行条件导出。

类似于:

export default connect(mstp, mdtp)(component1);

export let tests = {
  component1,
  component2,
  ...
};

if (process.env.NODE_ENV !==   "test") {
  tests = undefined;
}

然后在你的测试文件中做

import { tests} from ".";
const { component1, component2 } = tests;
//now test unconnected components

关于javascript - 导出一个函数只是为了测试被认为是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801617/

相关文章:

JavaScript - 当输入不是数字时提示

javascript - 获取没有边的节点

javascript - 哪里可以找到 V8 DOM 方法实现(document.createElement())的 "javascript"源代码?

mysql - 使用 sails 作为 REST API 的 Sails passport js 集成

javascript - 从今天起获得先前值(value)的最佳方式

node.js - npm 不支持 Node.js

javascript - 如何创建一个可以在其他模块中编辑而不是全局的变量?

javascript - 获取 props in action -> reducer -> 自定义函数

reactjs - React 无法将 undefined 或 null 转换为对象

reactjs - 是否可以在 formik 的密码字段上显示大写锁定指示符?