【问题标题】:How to enable babel-plugin-rewire in Meteor如何在 Meteor 中启用 babel-plugin-rewire
【发布时间】:2019-03-26 09:26:59
【问题描述】:

我正在尝试使用 babel-plugin-rewire 来模拟另一个文件中的函数。该函数不会被导出,而是由该文件的默认导出调用。

流星 1.6.1

"babel-plugin-rewire": "^1.2.0"

meteortesting:mocha@1.1.2

在我应用的 package.json 中:

  "babel": {
    "presets": ["latest", "meteor"],
    "env": {
      "test": {
        "plugins": [
          "babel-plugin-rewire"
        ]
      }
    }
  }

在我的 parentFunction.js 中:

import { some function } from 'anotherFile';

function childFunction() {
  ...
  return someValue;
}

export default function parentFunction() {
  return childFunction()
}

在我的测试文件中:

import { childFunction, __RewireAPI__ as MyRewireAPI } from './parentFunction'; // eslint-disable-line import/named

if (Meteor.isServer) {
  ...

  describe('parentFunction', () => {
    it('uses the mocked child function', () => {
      MyRewireAPI.__Rewire__('childFunction', function () {
        return Promise.resolve({ 'name': 'bob' });
            });
    });
  });
}

当我使用这个命令运行测试时:

TEST_WATCH=1 meteor test --driver-package meteortesting:mocha

我的所有其他测试都通过了,但这个失败并出现错误:

TypeError: Cannot read property '__Rewire__' of undefined

我认为 rewire 的重点是它从文件中获取了一个未导出的模块,所以这是否意味着 rewire 没有运行?我还需要做些什么来将 rewire 插件与 Meteor 的内置 babel 连接起来吗?

我已阅读文档并寻找其他类似问题,但看不出我做错了什么。对于我在这里缺少什么简单的东西的建议,我将非常感激。

编辑:我意识到我没有将 BABEL_ENV 环境变量设置为“测试”,但现在我设置了,但它仍然不起作用。

【问题讨论】:

  • 你的错误是因为import { childFunction, __RewireAPI__ as MyRewireAPI } from './parentFunction';没有导入MyRewireAPI
  • 对不起,我不明白。我应该写什么?

标签: javascript testing meteor mocha.js


【解决方案1】:

我今天也尝试用 Meteor 重新连接模块,但运气不好。

这可能是一个不错的选择。 只需像这样有条件地导出被测函数:

import { some function } from 'anotherFile';

function childFunction() {
  ...
  return someValue;
}

export default function parentFunction() {
  return childFunction()
}

if (Meteor.isTest || Meteor.isAppTest) {
    module.exports = { childFunction };
}

【讨论】:

    猜你喜欢
    • 2018-08-27
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2018-08-08
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多