的全局对象, code>我暴露了所有的类内进行测试。例如,在coffeescript中: class Query // ... 建议 // ... //使用类 //显示测试的类 window._test = {查询:查询建议:建议} ,我可以揭示我测试的类: Query = window._test.Query 描述'查询', - > // ... 这样做的好处是只有 _test 对象被污染,并且它不太可能与此对象的另一个定义发生冲突。它仍然不如我想要的那么干净,虽然。我希望有人能提供一个更好的解决方案。解决方案我认为像CommonJS模块系统href =http://brunch.io/ =nofollow> brunch )。 您可以将代码并且需要它们的部分将通过 require 导入它们。唯一受到污染的部分是模块管理代码维护的模块映射,非常类似于你的 test 对象。 在 Autocomplete.coffee class exports.Query // ... class exports.Suggestion // ... ,然后在 Autocomplete.spec.coffee {Query,Suggestion} = require'app / models / Autocomplete' describe'Query', - > I have a javascript autocomplete plugin that uses the following classes (written in coffeescript): Query, Suggestion, SuggestionCollection, and Autocomplete. Each of these classes has an associated spec written in Jasmine.The plugin is defined within a module, e.g.:(function(){ // plugin...}).call(this);This prevents the classes from polluting the global namespace, but also hides them from any tests (specs with jasmine, or unit-tests with something like q-unit).What is the best way to expose javascript classes or objects for testing without polluting the global namespace?I'll answer with the solution I came up with, but I'm hoping that there is something more standard.Update: My Attempted SolutionBecause I'm a newb with < 100 xp, I can't answer my own question for 8 hours. Instead of waiting I'll just add what I did here.In order to spec these classes, I invented a global object called _test that I exposed all the classes within for testing. For example, in coffeescript:class Query // ...class Suggestion // ...// Use the classes// Expose the classes for testingwindow._test = { Query: Query Suggestion: Suggestion}Inside my specs, then, I can reveal the class I'm testing:Query = window._test.Querydescribe 'Query', -> // ...This has the advantage that only the _test object is polluted, and it is unlikely it will collide with another definition of this object. It is still not as clean as I would like it, though. I'm hoping someone will provide a better solution. 解决方案 I think something like the CommonJS module system (as used by brunch, for example) would work.You can separate your code into modules, and the parts that need them would import them via require. The only part that gets "polluted" is the module map maintained by the module management code, very similar to your test object.In Autocomplete.coffeeclass exports.Query// ...class exports.Suggestion// ...and then in Autocomplete.spec.coffee{Query, Suggestion} = require 'app/models/Autocomplete'describe 'Query', -> 这篇关于如何暴露JavaScript对象进行单元测试,而不会污染全局命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!