【发布时间】:2019-07-12 08:17:17
【问题描述】:
我在 node.js 应用程序中有一个独立的 javascript 文件 cacheBustingInterceptor.js。它是一种工厂模式的服务,当应用程序持有时由 app.js 调用。
/**
* Intercept the http request
* If the config.url is from upload or templates and is a html file
* append the cacheBusting Param
* If the template url has query param exisitng
* append &_dt=epochtime else append ?_dt=epochtime
*/
var cacheBustingInterceptor = {
CacheBustingService: CacheBustingServiceFactory
};
function CacheBustingServiceFactory() {
function CacheBustingService() {}
var possibleHtmlPaths = ['templates', 'upload'];
CacheBustingService.prototype.appendCacheBustingParam = function(templateUrl) {
for (var index = 0; index != possibleHtmlPaths.length; index++) {
// check if the url has is .html and from upload and templates
var addCacheBusting = templateUrl.indexOf(possibleHtmlPaths[index]) != - 1 &&
templateUrl.indexOf('.html') != - 1;
var hasQueryParams = templateUrl.indexOf('?') != -1;
if (addCacheBusting) {
if (hasQueryParams) {
return templateUrl + window.appendCacheBustingParam;
} else {
return templateUrl + window.cacheBustingParam;
}
}
}
return templateUrl;
};
CacheBustingService.prototype.interceptRequest = function() {
var _this = this;
var cacheBuster = {
request: function (config) {
config.url = _this.appendCacheBustingParam(config.url);
return config;
}
}
return cacheBuster;
}
return CacheBustingService;
}
我们调用它的方式是在配置中的 app.js 中添加一个注入器,并将工厂推送到配置中。
像这样,
app. config([''$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('templateCacheBustingInjector');
app.factory('templateCacheBustingInjector', ['$injector', function
($injector) {
var CacheBustingService =
$injector.invoke(cacheBustingInterceptor.CacheBustingService);
var cacheBustingService = new CacheBustingService();
return cacheBustingService.interceptRequest();
}]);
现在一切正常,但我想在 cacheBustingInterceptor.js 中对方法 'appendCacheBustingParam' 进行单元测试,并且没有办法从 jasmine 单元测试中调用它
事情累了: 1.调用我在app.js中调用的方式,但是出现服务注入错误或者提供者错误 2.使用require加载js文件,但不支持require,我尝试使用browsify,但是也没有帮助。
require('../main/webapp/media/scripts/cacheBustingInterceptor.js');
fdescribe('Cache Busting Service', function() {
var cacheBustingService;
var $injector;
beforeEach((inject(function (_$injector_) {
$injector = _$injector_;
$injector.get(cacheBustingInterceptor.CacheBustingService);
// var CacheBustingService = $injector.invoke(cacheBustingInterceptor.CacheBustingService);
})));
it('Test appendCacheBustingParam', function() {
cacheBustingService = new CacheBustingService();
spyOn(cacheBustingService.prototype, 'appendCacheBustingParam');
expect(cacheBustingService.prototype).toHaveBeenCalled();
});
});
【问题讨论】:
-
由于 CacheBustingService 以任何方式与 AngularJS 一起使用,因此将其编写为提供程序是有意义的。如果您像往常一样使用 DI,就不会在测试时遇到此类问题。此外,答案已经包含有关此代码的有效点。
标签: javascript node.js jasmine karma-jasmine karma-runner