X Tutup
Skip to content

Commit a596b88

Browse files
committed
feat(compiler): Add an implementation for XHR that uses a template cache to load template files.
Useful for avoiding doing an actual XHR during testing. Part of the solution for #4051 (Other part is a Karma plugin that will create the template cache). Closes #7940
1 parent 6cbf990 commit a596b88

File tree

9 files changed

+194
-4
lines changed

9 files changed

+194
-4
lines changed

modules/angular2/platform/browser.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint';
22
export {
33
BROWSER_PROVIDERS,
4+
CACHED_TEMPLATE_PROVIDER,
45
ELEMENT_PROBE_PROVIDERS,
56
ELEMENT_PROBE_PROVIDERS_PROD_MODE,
67
inspectNativeElement,

modules/angular2/platform/testing/browser.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,15 @@ import {
22
TEST_BROWSER_STATIC_PLATFORM_PROVIDERS,
33
ADDITIONAL_TEST_BROWSER_PROVIDERS
44
} from 'angular2/platform/testing/browser_static';
5-
65
import {BROWSER_APP_PROVIDERS} from 'angular2/platform/browser';
7-
8-
96
import {CONST_EXPR} from 'angular2/src/facade/lang';
107

8+
/**
9+
* Providers for using template cache to avoid actual XHR.
10+
* Re-exported here so that tests import from a single place.
11+
*/
12+
export {CACHED_TEMPLATE_PROVIDER} from 'angular2/platform/browser';
13+
1114
/**
1215
* Default patform providers for testing.
1316
*/
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
library angular2.src.services.xhr_cache;
2+
3+
import 'dart:async' show Future;
4+
import 'dart:html';
5+
import 'dart:js' as js;
6+
import 'package:angular2/core.dart';
7+
import 'package:angular2/src/compiler/xhr.dart';
8+
import 'package:angular2/src/facade/exceptions.dart' show BaseException;
9+
10+
/**
11+
* An implementation of XHR that uses a template cache to avoid doing an actual
12+
* XHR.
13+
*
14+
* The template cache needs to be built and loaded into window.$templateCache
15+
* via a separate mechanism.
16+
*/
17+
@Injectable()
18+
class CachedXHR extends XHR {
19+
js.JsObject _cache;
20+
String _baseUri;
21+
22+
CachedXHR() {
23+
if (js.context.hasProperty(r'$templateCache')) {
24+
this._cache = js.context[r'$templateCache'];
25+
} else {
26+
throw new BaseException(
27+
r'CachedXHR: Template cache was not found in $templateCache.');
28+
}
29+
this._baseUri = window.location.protocol +
30+
'//' +
31+
window.location.host +
32+
window.location.pathname;
33+
int lastSlash = this._baseUri.lastIndexOf('/');
34+
this._baseUri = this._baseUri.substring(0, lastSlash + 1);
35+
}
36+
37+
Future<String> get(String url) {
38+
if (url.startsWith(this._baseUri)) {
39+
url = url.substring(this._baseUri.length);
40+
}
41+
if (this._cache.hasProperty(url)) {
42+
return new Future.value(this._cache[url]);
43+
} else {
44+
return new Future.error(
45+
'CachedXHR: Did not find cached template for ' + url);
46+
}
47+
}
48+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import {XHR} from 'angular2/src/compiler/xhr';
2+
import {BaseException} from 'angular2/src/facade/exceptions';
3+
import {global} from 'angular2/src/facade/lang';
4+
import {PromiseWrapper} from 'angular2/src/facade/promise';
5+
6+
/**
7+
* An implementation of XHR that uses a template cache to avoid doing an actual
8+
* XHR.
9+
*
10+
* The template cache needs to be built and loaded into window.$templateCache
11+
* via a separate mechanism.
12+
*/
13+
export class CachedXHR extends XHR {
14+
private _cache: {[url: string]: string};
15+
16+
constructor() {
17+
super();
18+
this._cache = (<any>global).$templateCache;
19+
if (this._cache == null) {
20+
throw new BaseException('CachedXHR: Template cache was not found in $templateCache.');
21+
}
22+
}
23+
24+
get(url: string): Promise<string> {
25+
if (this._cache.hasOwnProperty(url)) {
26+
return PromiseWrapper.resolve(this._cache[url]);
27+
} else {
28+
return PromiseWrapper.reject('CachedXHR: Did not find cached template for ' + url, null);
29+
}
30+
}
31+
}

modules/angular2/src/platform/browser_common.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import {CONST_EXPR, IS_DART} from 'angular2/src/facade/lang';
22
import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di';
3-
3+
import {XHR} from 'angular2/src/compiler/xhr';
44
import {
55
PLATFORM_INITIALIZER,
66
PLATFORM_DIRECTIVES,
@@ -28,6 +28,7 @@ import {BrowserDetails} from "angular2/src/animate/browser_details";
2828
import {AnimationBuilder} from "angular2/src/animate/animation_builder";
2929
import {BrowserDomAdapter} from './browser/browser_adapter';
3030
import {BrowserGetTestability} from 'angular2/src/platform/browser/testability';
31+
import {CachedXHR} from 'angular2/src/platform/browser/xhr_cache';
3132
import {wtfInit} from 'angular2/src/core/profile/wtf_init';
3233
import {EventManager, EVENT_MANAGER_PLUGINS} from "angular2/src/platform/dom/events/event_manager";
3334
import {
@@ -94,6 +95,9 @@ export const BROWSER_APP_COMMON_PROVIDERS: Array<any /*Type | Provider | any[]*/
9495
ELEMENT_PROBE_PROVIDERS
9596
]);
9697

98+
export const CACHED_TEMPLATE_PROVIDER: Array<any /*Type | Provider | any[]*/> =
99+
CONST_EXPR([new Provider(XHR, {useClass: CachedXHR})]);
100+
97101
export function initDomAdapter() {
98102
BrowserDomAdapter.makeCurrent();
99103
wtfInit();
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import 'dart:js' as js;
2+
3+
void setTemplateCache(Map cache) {
4+
if (cache == null) {
5+
if (js.context.hasProperty(r'$templateCache')) {
6+
js.context.deleteProperty(r'$templateCache');
7+
}
8+
return;
9+
}
10+
11+
js.JsObject jsMap = new js.JsObject(js.context['Object']);
12+
for (String key in cache.keys) {
13+
jsMap[key] = cache[key];
14+
}
15+
js.context[r'$templateCache'] = jsMap;
16+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function setTemplateCache(cache): void {
2+
(<any>window).$templateCache = cache;
3+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import {Component, provide} from 'angular2/core';
2+
import {UrlResolver, XHR} from 'angular2/compiler';
3+
import {
4+
AsyncTestCompleter,
5+
beforeEach,
6+
beforeEachProviders,
7+
ComponentFixture,
8+
ddescribe,
9+
describe,
10+
expect,
11+
fakeAsync,
12+
iit,
13+
inject,
14+
it,
15+
TestComponentBuilder,
16+
tick,
17+
xit
18+
} from 'angular2/testing_internal';
19+
import {BaseException} from 'angular2/src/facade/exceptions';
20+
import {CachedXHR} from 'angular2/src/platform/browser/xhr_cache';
21+
import {setTemplateCache} from './xhr_cache_setter';
22+
23+
export function main() {
24+
describe('CachedXHR', () => {
25+
var xhr: CachedXHR;
26+
27+
function createCachedXHR(): CachedXHR {
28+
setTemplateCache({'test.html': '<div>Hello</div>'});
29+
return new CachedXHR();
30+
}
31+
beforeEachProviders(() => [
32+
provide(UrlResolver, {useClass: TestUrlResolver}),
33+
provide(XHR, {useFactory: createCachedXHR})
34+
]);
35+
36+
it('should throw exception if $templateCache is not found', () => {
37+
setTemplateCache(null);
38+
expect(() => { xhr = new CachedXHR(); })
39+
.toThrowErrorWith('CachedXHR: Template cache was not found in $templateCache.');
40+
});
41+
42+
it('should resolve the Promise with the cached file content on success',
43+
inject([AsyncTestCompleter], (async) => {
44+
setTemplateCache({'test.html': '<div>Hello</div>'});
45+
xhr = new CachedXHR();
46+
xhr.get('test.html')
47+
.then((text) => {
48+
expect(text).toEqual('<div>Hello</div>');
49+
async.done();
50+
});
51+
}));
52+
53+
it('should reject the Promise on failure', inject([AsyncTestCompleter], (async) => {
54+
xhr = new CachedXHR();
55+
xhr.get('unknown.html')
56+
.then((text) => { throw new BaseException('Not expected to succeed.'); })
57+
.catch((error) => { async.done(); });
58+
}));
59+
60+
it('should allow fakeAsync Tests to load components with templateUrl synchronously',
61+
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => {
62+
let fixture: ComponentFixture;
63+
tcb.createAsync(TestComponent).then((f) => { fixture = f; });
64+
65+
// This should initialize the fixture.
66+
tick();
67+
68+
expect(fixture.debugElement.children[0].nativeElement).toHaveText('Hello');
69+
})));
70+
});
71+
}
72+
73+
@Component({selector: 'test-cmp', templateUrl: 'test.html'})
74+
class TestComponent {
75+
}
76+
77+
class TestUrlResolver extends UrlResolver {
78+
resolve(baseUrl: string, url: string): string {
79+
// Don't use baseUrl to get the same URL as templateUrl.
80+
// This is to remove any difference between Dart and TS tests.
81+
return url;
82+
}
83+
}

modules/angular2/test/public_api_spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,7 @@ var NG_PLATFORM_BROWSER = [
288288
'BROWSER_PROVIDERS',
289289
'BrowserDomAdapter',
290290
'By',
291+
'CACHED_TEMPLATE_PROVIDER',
291292
'DOCUMENT',
292293
'ELEMENT_PROBE_PROVIDERS',
293294
'ELEMENT_PROBE_PROVIDERS_PROD_MODE',

0 commit comments

Comments
 (0)
X Tutup