- I have a web application that uses window.applicationCache for offline access.
- All of my code that manages the appCache (eg. checking/updating/swapping the cache) is encapsulated into a "cache-controller" object.
I have unit tests to test my "cache-controller" functions. For testing, I temporarily replace the native window.applicationCache object with my own mock version (since I only want to test my code, not the browsers appCache implementation), eg.
window.applicationCache = { /* my appCache mock */ }; // unit tests run here. Code under test references window.applicationCache.
无论如何,我刚刚将我的应用程序从传统的“浏览器全局变量”(即通过脚本标记加载*.js文件;所有JS对象都是全局的)迁移到了AMD风格的模块,使用require.js作为模块加载器。
AMD(或CommonJS)的好处之一是依赖注入,其中您的代码获得对任何依赖对象的本地引用,而不是依赖于全局引用,例如。
require(['foo'], function(Foo) {
var bar = new Foo();
});
这使得对象模拟变得容易,因为您可以配置模块加载器,在测试模式下传递一个名为'foo'的模拟对象。
我曾希望通过使用依赖注入来解决我的applicationCache问题(因为传递给我的模块的“window”引用可以是全局窗口对象或模拟对象)。
然而,我不确定如何让require.js将“window”注入到我的模块中?
是否可能(也许使用shim config?)定义一个“window”模块;然后将其传递给任何操作全局“window”对象的代码?这样我就可以像这样做:
require(['???'], function(window) {
// 'window' here is the real window object, or for testing it's a mock window object
window.applicationCache.update();
});
...其中'???'是指代window对象的模块名称。
或者我需要定义自己的模块,导出'window',并且可以在单元测试中以不同的方式映射,例如。
// window.js
define(function() {
return window; // real global window object
});
// window-mock.js
define(function() {
return {
applicationCache: { /* mock version of appCache */ }
}
});
// for unit testing, remap 'window' to the mock version
require.config({
map: {
"cache-controller": {
"window": "window-mock"
}
}
});
// cache-controller.js
require(['window'], function(window) {
window.applicationCache.update();
});