Step 2: Hello World with Angular2
In this step, we are going to turn our basic HTML page into the simplest possible Angular2 version, complete with a unit test.
By the end of this step, we will have:
- A Unit Test Framework
- A Test to prove the existence of Angular2 in the page
- The H1 value provided by Angular2
Specification
- When viewed in a browser, the user will continue to see "Hello World!"
- The value for the H1 element will be provided by Angular2.
Discussion
Angular2 works with :
- TypeScript
- Javascript
- Dart
I will choose TypeScript. It is a typed superset of JavaScript, which offers static types.
Task Breakdown
- Add failing E2E test to prove existence of Angular2 on the HTML page.
- Add Angular2 to page so the test will pass.
2.1 Add failing E2E test to prove existence of Angular2 on HTML page
This change just turns on the expectation of Angular's presence in the test. Protractor was developed by the Angular team. By default, Protractor waits for Angular to finish loading before running the test. If Angular is not present, this times out and causes an error.
beforeAll(function() {
- isAngularSite(false);
+ isAngularSite(true);
browser.get('/');
});
For Angular2, you also need to add the useAllAngular2AppRoots option to the protractor options.
This means that Protractor will wait for every app to be stable before each action, and search within all apps when finding elements.
+ useAllAngular2AppRoots: true,
2.2. Add Angular2 to page so the test will pass
Add the angularjs scripts.
<head>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-alpha.44/angular2.dev.js"></script>
</head>
Add the angularjs loader.
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true }
});
</script>
Add the helloworld component code (helloworld.ts). This is written in TypeScript. The transpiler option above ensures that the TypeScript code is converted into JavaScript, so that it is understandable by more browsers.
System.import('./helloworld.ts');
helloworld.ts uses a separate file for the HTML template, helloworld.html.
<div>
<h1 id='h1'>Hello World!</h1>
</div>
Include the component in index.html.
<helloworld>loading...</helloworld>
Now we can run the Step2 test and it will pass.