使用 'export' 关键字仅用于导入单元测试
Using 'export' keyword solely for importing into Unit Tests
我正在使用 Meteor 并正在为 Collection 编写单元测试。除了常规的 JS 函数之外,我还有 collection 的辅助方法。
即
Collection.helpers({
helperFn: function () {
return 'foo';
}
});
//And in the same file
function bar() {
return "bar";
}
然后在我的测试文件中有类似
的内容
import { Collection } from '../collections'
//Use Factory or Stub to create test Document
//This then works just fine and I can assert, etc..
testDoc.helperFn
我的问题是只想测试常规 'bar' JS 函数。使用 ES6 classes 没什么大不了的,因为这样我就可以导出整个 class 并使用它的实例调用任何函数。但是对于 Meteor,我发现访问该函数的唯一方法是使用 'export' 关键字。
所以在我的 Collection 文件中
export function bar ({ return bar; });
现在在我的测试文件中我会做类似
的事情
import { bar } from '../collection'
我不想在每次测试新功能时都添加导出语句。有什么办法解决这个问题还是没什么大不了的?
我确实认为 export/import 是可行的方法,但要回答你问题的第一部分:是的,你可以回退到 meteor 的原始范围并将这些函数放在全局中meteor范围如下:
- 不要将您的文件放在
imports/
文件夹中,而是放在项目中的另一个文件夹中,例如 server/
.
- 将函数定义为:
bar = function() { /* function body */ }
这些变量被 meteor 解释为项目的全局变量,因此在使用前不需要导入。
也就是说,meteor 在 1.3 版中引入 imports/
文件夹和相应的 export/import 范式是有原因的。它避免了污染全局范围,并使查看定义的位置变得更加容易。
我正在使用 Meteor 并正在为 Collection 编写单元测试。除了常规的 JS 函数之外,我还有 collection 的辅助方法。
即
Collection.helpers({
helperFn: function () {
return 'foo';
}
});
//And in the same file
function bar() {
return "bar";
}
然后在我的测试文件中有类似
的内容import { Collection } from '../collections'
//Use Factory or Stub to create test Document
//This then works just fine and I can assert, etc..
testDoc.helperFn
我的问题是只想测试常规 'bar' JS 函数。使用 ES6 classes 没什么大不了的,因为这样我就可以导出整个 class 并使用它的实例调用任何函数。但是对于 Meteor,我发现访问该函数的唯一方法是使用 'export' 关键字。
所以在我的 Collection 文件中
export function bar ({ return bar; });
现在在我的测试文件中我会做类似
的事情import { bar } from '../collection'
我不想在每次测试新功能时都添加导出语句。有什么办法解决这个问题还是没什么大不了的?
我确实认为 export/import 是可行的方法,但要回答你问题的第一部分:是的,你可以回退到 meteor 的原始范围并将这些函数放在全局中meteor范围如下:
- 不要将您的文件放在
imports/
文件夹中,而是放在项目中的另一个文件夹中,例如server/
. - 将函数定义为:
这些变量被 meteor 解释为项目的全局变量,因此在使用前不需要导入。bar = function() { /* function body */ }
也就是说,meteor 在 1.3 版中引入 imports/
文件夹和相应的 export/import 范式是有原因的。它避免了污染全局范围,并使查看定义的位置变得更加容易。