简体   繁体   English

如何在 Meteor 中启用 babel-plugin-rewire

[英]How to enable babel-plugin-rewire in Meteor

I'm trying to use babel-plugin-rewire to mock a function inside another file.我正在尝试使用 babel-plugin-rewire 来模拟另一个文件中的函数。 This function is not exported, but is called by the default export from that file.此函数不导出,但由该文件的默认导出调用。

Meteor 1.6.1流星 1.6.1

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

meteortesting:mocha@1.1.2流星测试:mocha@1.1.2

in my app's package.json:在我的应用程序的 package.json 中:

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

In my parentFunction.js:在我的 parentFunction.js 中:

import { some function } from 'anotherFile';

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

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

In my test file:在我的测试文件中:

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' });
            });
    });
  });
}

When I run the tests with this command:当我使用此命令运行测试时:

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

All my other tests pass but this one fails with the error:我所有的其他测试都通过了,但这个测试失败并出现错误:

TypeError: Cannot read property '__Rewire__' of undefined

I thought the point of rewire is that it gets a non-exported module out of a file, so does this mean rewire isn't running?我认为 rewire 的重点是它从文件中获取一个非导出的模块,所以这是否意味着 rewire 没有运行? Is there something else I need to do to connect the rewire plugin with Meteor's built-in babel?我还需要做些什么来将 rewire 插件与 Meteor 的内置 babel 连接起来?

I've read the documentation and looked for other similar issues, and can't see what I'm doing wrong.我已经阅读了文档并寻找了其他类似的问题,但看不出我做错了什么。 I'd be very grateful for suggestions as to what simple thing I am missing here.我将非常感谢关于我在这里缺少什么简单的东西的建议。

Edit: I realised I wasn't setting the BABEL_ENV environment variable to 'test' but now I am, and it still doesn't work.编辑:我意识到我没有将 BABEL_ENV 环境变量设置为“test”,但现在我是,但它仍然不起作用。

I also tried rewire module with Meteor without luck today.我今天也试过用 Meteor 重新布线模块,但没有运气。

This might be a good alternative.这可能是一个不错的选择。 Just conditionally export the function under test like this:只需像这样有条件地导出被测函数:

import { some function } from 'anotherFile';

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM