refactor(docs-infra): fix docs examples for tslint rule prefer-const (#38143)

This commit updates the docs examples to be compatible with the
`prefer-const` tslint rule.

This is in preparation of updating the docs examples `tslint.json` to
match the one generated for new Angular CLI apps in a future commit.

PR Close #38143
This commit is contained in:
George Kalpakas 2020-07-30 13:03:19 +03:00 committed by Alex Rickabaugh
parent ba11f7b90b
commit 5303773daf
112 changed files with 601 additions and 601 deletions

View File

@ -12,7 +12,7 @@ describe('AngularJS to Angular Quick Reference Tests', () => {
it('should display proper movie data', () => { it('should display proper movie data', () => {
// We check only a few samples // We check only a few samples
let expectedSamples: any[] = [ const expectedSamples: any[] = [
{row: 0, column: 0, element: 'img', attr: 'src', value: 'images/hero.png', contains: true}, {row: 0, column: 0, element: 'img', attr: 'src', value: 'images/hero.png', contains: true},
{row: 0, column: 2, value: 'Celeritas'}, {row: 0, column: 2, value: 'Celeritas'},
{row: 1, column: 3, matches: /Dec 1[678], 2015/}, // absorb timezone dif; we care about date format {row: 1, column: 3, matches: /Dec 1[678], 2015/}, // absorb timezone dif; we care about date format
@ -23,18 +23,18 @@ describe('AngularJS to Angular Quick Reference Tests', () => {
]; ];
// Go through the samples // Go through the samples
let movieRows = getMovieRows(); const movieRows = getMovieRows();
for (let i = 0; i < expectedSamples.length; i++) { for (let i = 0; i < expectedSamples.length; i++) {
let sample = expectedSamples[i]; const sample = expectedSamples[i];
let tableCell = movieRows.get(sample.row) const tableCell = movieRows.get(sample.row)
.all(by.tagName('td')).get(sample.column); .all(by.tagName('td')).get(sample.column);
// Check the cell or its nested element // Check the cell or its nested element
let elementToCheck = sample.element const elementToCheck = sample.element
? tableCell.element(by.tagName(sample.element)) ? tableCell.element(by.tagName(sample.element))
: tableCell; : tableCell;
// Check element attribute or text // Check element attribute or text
let valueToCheck = sample.attr const valueToCheck = sample.attr
? elementToCheck.getAttribute(sample.attr) ? elementToCheck.getAttribute(sample.attr)
: elementToCheck.getText(); : elementToCheck.getText();
@ -70,18 +70,18 @@ describe('AngularJS to Angular Quick Reference Tests', () => {
}); });
function testImagesAreDisplayed(isDisplayed: boolean) { function testImagesAreDisplayed(isDisplayed: boolean) {
let expectedMovieCount = 3; const expectedMovieCount = 3;
let movieRows = getMovieRows(); const movieRows = getMovieRows();
expect(movieRows.count()).toBe(expectedMovieCount); expect(movieRows.count()).toBe(expectedMovieCount);
for (let i = 0; i < expectedMovieCount; i++) { for (let i = 0; i < expectedMovieCount; i++) {
let movieImage = movieRows.get(i).element(by.css('td > img')); const movieImage = movieRows.get(i).element(by.css('td > img'));
expect(movieImage.isDisplayed()).toBe(isDisplayed); expect(movieImage.isDisplayed()).toBe(isDisplayed);
} }
} }
function testPosterButtonClick(expectedButtonText: string, isDisplayed: boolean) { function testPosterButtonClick(expectedButtonText: string, isDisplayed: boolean) {
let posterButton = element(by.css('app-movie-list tr > th > button')); const posterButton = element(by.css('app-movie-list tr > th > button'));
expect(posterButton.getText()).toBe(expectedButtonText); expect(posterButton.getText()).toBe(expectedButtonText);
posterButton.click().then(() => { posterButton.click().then(() => {
@ -94,10 +94,10 @@ describe('AngularJS to Angular Quick Reference Tests', () => {
} }
function testFavoriteHero(heroName: string, expectedLabel: string) { function testFavoriteHero(heroName: string, expectedLabel: string) {
let movieListComp = element(by.tagName('app-movie-list')); const movieListComp = element(by.tagName('app-movie-list'));
let heroInput = movieListComp.element(by.tagName('input')); const heroInput = movieListComp.element(by.tagName('input'));
let favoriteHeroLabel = movieListComp.element(by.tagName('h3')); const favoriteHeroLabel = movieListComp.element(by.tagName('h3'));
let resultLabel = movieListComp.element(by.css('span > p')); const resultLabel = movieListComp.element(by.css('span > p'));
heroInput.clear().then(() => { heroInput.clear().then(() => {
heroInput.sendKeys(heroName || ''); heroInput.sendKeys(heroName || '');

View File

@ -19,7 +19,7 @@ describe('Architecture', () => {
}); });
it(`has h2 '${expectedH2}'`, () => { it(`has h2 '${expectedH2}'`, () => {
let h2 = element.all(by.css('h2')).map((elt: any) => elt.getText()); const h2 = element.all(by.css('h2')).map((elt: any) => elt.getText());
expect(h2).toEqual(expectedH2); expect(h2).toEqual(expectedH2);
}); });
@ -32,29 +32,29 @@ function heroTests() {
const targetHero: Hero = { id: 2, name: 'Dr Nice' }; const targetHero: Hero = { id: 2, name: 'Dr Nice' };
it('has the right number of heroes', () => { it('has the right number of heroes', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.heroes.count()).toEqual(3); expect(page.heroes.count()).toEqual(3);
}); });
it('has no hero details initially', () => { it('has no hero details initially', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail'); expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail');
}); });
it('shows selected hero details', async () => { it('shows selected hero details', async () => {
await element(by.cssContainingText('li', targetHero.name)).click(); await element(by.cssContainingText('li', targetHero.name)).click();
let page = getPageElts(); const page = getPageElts();
let hero = await heroFromDetail(page.heroDetail); const hero = await heroFromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name); expect(hero.name).toEqual(targetHero.name);
}); });
it(`shows updated hero name in details`, async () => { it(`shows updated hero name in details`, async () => {
let input = element.all(by.css('input')).first(); const input = element.all(by.css('input')).first();
input.sendKeys(nameSuffix); input.sendKeys(nameSuffix);
let page = getPageElts(); const page = getPageElts();
let hero = await heroFromDetail(page.heroDetail); const hero = await heroFromDetail(page.heroDetail);
let newName = targetHero.name + nameSuffix; const newName = targetHero.name + nameSuffix;
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newName); expect(hero.name).toEqual(newName);
}); });
@ -62,12 +62,12 @@ function heroTests() {
function salesTaxTests() { function salesTaxTests() {
it('has no sales tax initially', () => { it('has no sales tax initially', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.salesTaxDetail.isPresent()).toBeFalsy('no sales tax info'); expect(page.salesTaxDetail.isPresent()).toBeFalsy('no sales tax info');
}); });
it('shows sales tax', async () => { it('shows sales tax', async () => {
let page = getPageElts(); const page = getPageElts();
page.salesTaxAmountInput.sendKeys('10', protractor.Key.ENTER); page.salesTaxAmountInput.sendKeys('10', protractor.Key.ENTER);
expect(page.salesTaxDetail.getText()).toEqual('The sales tax is $1.00'); expect(page.salesTaxDetail.getText()).toEqual('The sales tax is $1.00');
}); });
@ -86,9 +86,9 @@ function getPageElts() {
async function heroFromDetail(detail: ElementFinder): Promise<Hero> { async function heroFromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div> // Get hero id from the first <div>
let id = await detail.all(by.css('div')).first().getText(); const id = await detail.all(by.css('div')).first().getText();
// Get name from the h2 // Get name from the h2
let name = await detail.element(by.css('h4')).getText(); const name = await detail.element(by.css('h4')).getText();
return { return {
id: +id.substr(id.indexOf(' ') + 1), id: +id.substr(id.indexOf(' ') + 1),
name: name.substr(0, name.lastIndexOf(' ')), name: name.substr(0, name.lastIndexOf(' ')),

View File

@ -18,7 +18,7 @@ export class BackendService {
// TODO: get from the database // TODO: get from the database
return Promise.resolve<Hero[]>(HEROES); return Promise.resolve<Hero[]>(HEROES);
} }
let err = new Error('Cannot get object of this type'); const err = new Error('Cannot get object of this type');
this.logger.error(err); this.logger.error(err);
throw err; throw err;
} }

View File

@ -7,7 +7,7 @@ export class SalesTaxService {
constructor(private rateService: TaxRateService) { } constructor(private rateService: TaxRateService) { }
getVAT(value: string | number) { getVAT(value: string | number) {
let amount = (typeof value === 'string') ? const amount = (typeof value === 'string') ?
parseFloat(value) : value; parseFloat(value) : value;
return (amount || 0) * this.rateService.getRate('VAT'); return (amount || 0) * this.rateService.getRate('VAT');
} }

View File

@ -2,7 +2,7 @@ import { browser, element, by } from 'protractor';
describe('Attribute directives', () => { describe('Attribute directives', () => {
let title = 'My First Attribute Directive'; const title = 'My First Attribute Directive';
beforeAll(() => { beforeAll(() => {
browser.get(''); browser.get('');

View File

@ -36,22 +36,22 @@ describe('Binding syntax e2e tests', () => {
it('should log a message including Sarah', async () => { it('should log a message including Sarah', async () => {
let attributeButton = element.all(by.css('button')).get(1); const attributeButton = element.all(by.css('button')).get(1);
await attributeButton.click(); await attributeButton.click();
const contents = 'Sarah'; const contents = 'Sarah';
logChecker(attributeButton, contents); logChecker(attributeButton, contents);
}); });
it('should log a message including Sarah for DOM property', async () => { it('should log a message including Sarah for DOM property', async () => {
let DOMPropertyButton = element.all(by.css('button')).get(2); const DOMPropertyButton = element.all(by.css('button')).get(2);
await DOMPropertyButton.click(); await DOMPropertyButton.click();
const contents = 'Sarah'; const contents = 'Sarah';
logChecker(DOMPropertyButton, contents); logChecker(DOMPropertyButton, contents);
}); });
it('should log a message including Sally for DOM property', async () => { it('should log a message including Sally for DOM property', async () => {
let DOMPropertyButton = element.all(by.css('button')).get(2); const DOMPropertyButton = element.all(by.css('button')).get(2);
let input = element(by.css('input')); const input = element(by.css('input'));
input.sendKeys('Sally'); input.sendKeys('Sally');
await DOMPropertyButton.click(); await DOMPropertyButton.click();
const contents = 'Sally'; const contents = 'Sally';
@ -59,14 +59,14 @@ describe('Binding syntax e2e tests', () => {
}); });
it('should log a message that Test Button works', async () => { it('should log a message that Test Button works', async () => {
let testButton = element.all(by.css('button')).get(3); const testButton = element.all(by.css('button')).get(3);
await testButton.click(); await testButton.click();
const contents = 'Test'; const contents = 'Test';
logChecker(testButton, contents); logChecker(testButton, contents);
}); });
it('should toggle Test Button disabled', async () => { it('should toggle Test Button disabled', async () => {
let toggleButton = element.all(by.css('button')).get(4); const toggleButton = element.all(by.css('button')).get(4);
await toggleButton.click(); await toggleButton.click();
const contents = 'true'; const contents = 'true';
logChecker(toggleButton, contents); logChecker(toggleButton, contents);

View File

@ -26,7 +26,7 @@ export class AppComponent {
toggleDisabled(): any { toggleDisabled(): any {
let testButton = document.getElementById('testButton') as HTMLInputElement; const testButton = document.getElementById('testButton') as HTMLInputElement;
testButton.disabled = !testButton.disabled; testButton.disabled = !testButton.disabled;
console.warn(testButton.disabled); console.warn(testButton.disabled);
} }

View File

@ -7,13 +7,13 @@ describe('Built-in Directives', () => {
}); });
it('should have title Built-in Directives', () => { it('should have title Built-in Directives', () => {
let title = element.all(by.css('h1')).get(0); const title = element.all(by.css('h1')).get(0);
expect(title.getText()).toEqual('Built-in Directives'); expect(title.getText()).toEqual('Built-in Directives');
}); });
it('should change first Teapot header', async () => { it('should change first Teapot header', async () => {
let firstLabel = element.all(by.css('p')).get(0); const firstLabel = element.all(by.css('p')).get(0);
let firstInput = element.all(by.css('input')).get(0); const firstInput = element.all(by.css('input')).get(0);
expect(firstLabel.getText()).toEqual('Current item name: Teapot'); expect(firstLabel.getText()).toEqual('Current item name: Teapot');
firstInput.sendKeys('abc'); firstInput.sendKeys('abc');
@ -22,48 +22,48 @@ describe('Built-in Directives', () => {
it('should modify sentence when modified checkbox checked', () => { it('should modify sentence when modified checkbox checked', () => {
let modifiedChkbxLabel = element.all(by.css('input[type="checkbox"]')).get(1); const modifiedChkbxLabel = element.all(by.css('input[type="checkbox"]')).get(1);
let modifiedSentence = element.all(by.css('div')).get(1); const modifiedSentence = element.all(by.css('div')).get(1);
modifiedChkbxLabel.click(); modifiedChkbxLabel.click();
expect(modifiedSentence.getText()).toContain('modified'); expect(modifiedSentence.getText()).toContain('modified');
}); });
it('should modify sentence when normal checkbox checked', () => { it('should modify sentence when normal checkbox checked', () => {
let normalChkbxLabel = element.all(by.css('input[type="checkbox"]')).get(4); const normalChkbxLabel = element.all(by.css('input[type="checkbox"]')).get(4);
let normalSentence = element.all(by.css('div')).get(7); const normalSentence = element.all(by.css('div')).get(7);
normalChkbxLabel.click(); normalChkbxLabel.click();
expect(normalSentence.getText()).toContain('normal weight and, extra large'); expect(normalSentence.getText()).toContain('normal weight and, extra large');
}); });
it('should toggle app-item-detail', () => { it('should toggle app-item-detail', () => {
let toggleButton = element.all(by.css('button')).get(3); const toggleButton = element.all(by.css('button')).get(3);
let toggledDiv = element.all(by.css('app-item-detail')).get(0); const toggledDiv = element.all(by.css('app-item-detail')).get(0);
toggleButton.click(); toggleButton.click();
expect(toggledDiv.isDisplayed()).toBe(true); expect(toggledDiv.isDisplayed()).toBe(true);
}); });
it('should hide app-item-detail', () => { it('should hide app-item-detail', () => {
let hiddenMessage = element.all(by.css('p')).get(11); const hiddenMessage = element.all(by.css('p')).get(11);
let hiddenDiv = element.all(by.css('app-item-detail')).get(2); const hiddenDiv = element.all(by.css('app-item-detail')).get(2);
expect(hiddenMessage.getText()).toContain('in the DOM'); expect(hiddenMessage.getText()).toContain('in the DOM');
expect(hiddenDiv.isDisplayed()).toBe(true); expect(hiddenDiv.isDisplayed()).toBe(true);
}); });
it('should have 10 lists each containing the string Teapot', () => { it('should have 10 lists each containing the string Teapot', () => {
let listDiv = element.all(by.cssContainingText('.box', 'Teapot')); const listDiv = element.all(by.cssContainingText('.box', 'Teapot'));
expect(listDiv.count()).toBe(10); expect(listDiv.count()).toBe(10);
}); });
it('should switch case', () => { it('should switch case', () => {
let tvRadioButton = element.all(by.css('input[type="radio"]')).get(3); const tvRadioButton = element.all(by.css('input[type="radio"]')).get(3);
let tvDiv = element(by.css('app-lost-item')); const tvDiv = element(by.css('app-lost-item'));
let fishbowlRadioButton = element.all(by.css('input[type="radio"]')).get(4); const fishbowlRadioButton = element.all(by.css('input[type="radio"]')).get(4);
let fishbowlDiv = element(by.css('app-unknown-item')); const fishbowlDiv = element(by.css('app-unknown-item'));
tvRadioButton.click(); tvRadioButton.click();
expect(tvDiv.getText()).toContain('Television'); expect(tvDiv.getText()).toContain('Television');

View File

@ -6,12 +6,12 @@ describe('Built Template Functions Example', () => {
}); });
it('should have title Built-in Template Functions', () => { it('should have title Built-in Template Functions', () => {
let title = element.all(by.css('h1')).get(0); const title = element.all(by.css('h1')).get(0);
expect(title.getText()).toEqual('Built-in Template Functions'); expect(title.getText()).toEqual('Built-in Template Functions');
}); });
it('should display $any( ) in h2', () => { it('should display $any( ) in h2', () => {
let header = element(by.css('h2')); const header = element(by.css('h2'));
expect(header.getText()).toContain('$any( )'); expect(header.getText()).toContain('$any( )');
}); });

View File

@ -11,16 +11,16 @@ describe('Component Communication Cookbook Tests', () => {
describe('Parent-to-child communication', () => { describe('Parent-to-child communication', () => {
// #docregion parent-to-child // #docregion parent-to-child
// ... // ...
let heroNames = ['Dr IQ', 'Magneta', 'Bombasto']; const heroNames = ['Dr IQ', 'Magneta', 'Bombasto'];
let masterName = 'Master'; const masterName = 'Master';
it('should pass properties to children properly', () => { it('should pass properties to children properly', () => {
let parent = element.all(by.tagName('app-hero-parent')).get(0); const parent = element.all(by.tagName('app-hero-parent')).get(0);
let heroes = parent.all(by.tagName('app-hero-child')); const heroes = parent.all(by.tagName('app-hero-child'));
for (let i = 0; i < heroNames.length; i++) { for (let i = 0; i < heroNames.length; i++) {
let childTitle = heroes.get(i).element(by.tagName('h3')).getText(); const childTitle = heroes.get(i).element(by.tagName('h3')).getText();
let childDetail = heroes.get(i).element(by.tagName('p')).getText(); const childDetail = heroes.get(i).element(by.tagName('p')).getText();
expect(childTitle).toEqual(heroNames[i] + ' says:'); expect(childTitle).toEqual(heroNames[i] + ' says:');
expect(childDetail).toContain(masterName); expect(childDetail).toContain(masterName);
} }
@ -33,22 +33,22 @@ describe('Component Communication Cookbook Tests', () => {
// #docregion parent-to-child-setter // #docregion parent-to-child-setter
// ... // ...
it('should display trimmed, non-empty names', () => { it('should display trimmed, non-empty names', () => {
let nonEmptyNameIndex = 0; const nonEmptyNameIndex = 0;
let nonEmptyName = '"Dr IQ"'; const nonEmptyName = '"Dr IQ"';
let parent = element.all(by.tagName('app-name-parent')).get(0); const parent = element.all(by.tagName('app-name-parent')).get(0);
let hero = parent.all(by.tagName('app-name-child')).get(nonEmptyNameIndex); const hero = parent.all(by.tagName('app-name-child')).get(nonEmptyNameIndex);
let displayName = hero.element(by.tagName('h3')).getText(); const displayName = hero.element(by.tagName('h3')).getText();
expect(displayName).toEqual(nonEmptyName); expect(displayName).toEqual(nonEmptyName);
}); });
it('should replace empty name with default name', () => { it('should replace empty name with default name', () => {
let emptyNameIndex = 1; const emptyNameIndex = 1;
let defaultName = '"<no name set>"'; const defaultName = '"<no name set>"';
let parent = element.all(by.tagName('app-name-parent')).get(0); const parent = element.all(by.tagName('app-name-parent')).get(0);
let hero = parent.all(by.tagName('app-name-child')).get(emptyNameIndex); const hero = parent.all(by.tagName('app-name-child')).get(emptyNameIndex);
let displayName = hero.element(by.tagName('h3')).getText(); const displayName = hero.element(by.tagName('h3')).getText();
expect(displayName).toEqual(defaultName); expect(displayName).toEqual(defaultName);
}); });
// ... // ...
@ -60,10 +60,10 @@ describe('Component Communication Cookbook Tests', () => {
// ... // ...
// Test must all execute in this exact order // Test must all execute in this exact order
it('should set expected initial values', () => { it('should set expected initial values', () => {
let actual = getActual(); const actual = getActual();
let initialLabel = 'Version 1.23'; const initialLabel = 'Version 1.23';
let initialLog = 'Initial value of major set to 1, Initial value of minor set to 23'; const initialLog = 'Initial value of major set to 1, Initial value of minor set to 23';
expect(actual.label).toBe(initialLabel); expect(actual.label).toBe(initialLabel);
expect(actual.count).toBe(1); expect(actual.count).toBe(1);
@ -71,15 +71,15 @@ describe('Component Communication Cookbook Tests', () => {
}); });
it('should set expected values after clicking \'Minor\' twice', () => { it('should set expected values after clicking \'Minor\' twice', () => {
let repoTag = element(by.tagName('app-version-parent')); const repoTag = element(by.tagName('app-version-parent'));
let newMinorButton = repoTag.all(by.tagName('button')).get(0); const newMinorButton = repoTag.all(by.tagName('button')).get(0);
newMinorButton.click().then(() => { newMinorButton.click().then(() => {
newMinorButton.click().then(() => { newMinorButton.click().then(() => {
let actual = getActual(); const actual = getActual();
let labelAfter2Minor = 'Version 1.25'; const labelAfter2Minor = 'Version 1.25';
let logAfter2Minor = 'minor changed from 24 to 25'; const logAfter2Minor = 'minor changed from 24 to 25';
expect(actual.label).toBe(labelAfter2Minor); expect(actual.label).toBe(labelAfter2Minor);
expect(actual.count).toBe(3); expect(actual.count).toBe(3);
@ -89,14 +89,14 @@ describe('Component Communication Cookbook Tests', () => {
}); });
it('should set expected values after clicking \'Major\' once', () => { it('should set expected values after clicking \'Major\' once', () => {
let repoTag = element(by.tagName('app-version-parent')); const repoTag = element(by.tagName('app-version-parent'));
let newMajorButton = repoTag.all(by.tagName('button')).get(1); const newMajorButton = repoTag.all(by.tagName('button')).get(1);
newMajorButton.click().then(() => { newMajorButton.click().then(() => {
let actual = getActual(); const actual = getActual();
let labelAfterMajor = 'Version 2.0'; const labelAfterMajor = 'Version 2.0';
let logAfterMajor = 'major changed from 1 to 2, minor changed from 25 to 0'; const logAfterMajor = 'major changed from 1 to 2, minor changed from 25 to 0';
expect(actual.label).toBe(labelAfterMajor); expect(actual.label).toBe(labelAfterMajor);
expect(actual.count).toBe(4); expect(actual.count).toBe(4);
@ -105,10 +105,10 @@ describe('Component Communication Cookbook Tests', () => {
}); });
function getActual() { function getActual() {
let versionTag = element(by.tagName('app-version-child')); const versionTag = element(by.tagName('app-version-child'));
let label = versionTag.element(by.tagName('h3')).getText(); const label = versionTag.element(by.tagName('h3')).getText();
let ul = versionTag.element((by.tagName('ul'))); const ul = versionTag.element((by.tagName('ul')));
let logs = ul.all(by.tagName('li')); const logs = ul.all(by.tagName('li'));
return { return {
label, label,
@ -125,26 +125,26 @@ describe('Component Communication Cookbook Tests', () => {
// #docregion child-to-parent // #docregion child-to-parent
// ... // ...
it('should not emit the event initially', () => { it('should not emit the event initially', () => {
let voteLabel = element(by.tagName('app-vote-taker')) const voteLabel = element(by.tagName('app-vote-taker'))
.element(by.tagName('h3')).getText(); .element(by.tagName('h3')).getText();
expect(voteLabel).toBe('Agree: 0, Disagree: 0'); expect(voteLabel).toBe('Agree: 0, Disagree: 0');
}); });
it('should process Agree vote', () => { it('should process Agree vote', () => {
let agreeButton1 = element.all(by.tagName('app-voter')).get(0) const agreeButton1 = element.all(by.tagName('app-voter')).get(0)
.all(by.tagName('button')).get(0); .all(by.tagName('button')).get(0);
agreeButton1.click().then(() => { agreeButton1.click().then(() => {
let voteLabel = element(by.tagName('app-vote-taker')) const voteLabel = element(by.tagName('app-vote-taker'))
.element(by.tagName('h3')).getText(); .element(by.tagName('h3')).getText();
expect(voteLabel).toBe('Agree: 1, Disagree: 0'); expect(voteLabel).toBe('Agree: 1, Disagree: 0');
}); });
}); });
it('should process Disagree vote', () => { it('should process Disagree vote', () => {
let agreeButton1 = element.all(by.tagName('app-voter')).get(1) const agreeButton1 = element.all(by.tagName('app-voter')).get(1)
.all(by.tagName('button')).get(1); .all(by.tagName('button')).get(1);
agreeButton1.click().then(() => { agreeButton1.click().then(() => {
let voteLabel = element(by.tagName('app-vote-taker')) const voteLabel = element(by.tagName('app-vote-taker'))
.element(by.tagName('h3')).getText(); .element(by.tagName('h3')).getText();
expect(voteLabel).toBe('Agree: 1, Disagree: 1'); expect(voteLabel).toBe('Agree: 1, Disagree: 1');
}); });
@ -167,19 +167,19 @@ describe('Component Communication Cookbook Tests', () => {
// #docregion countdown-timer-tests // #docregion countdown-timer-tests
// ... // ...
it('timer and parent seconds should match', () => { it('timer and parent seconds should match', () => {
let parent = element(by.tagName(parentTag)); const parent = element(by.tagName(parentTag));
let message = parent.element(by.tagName('app-countdown-timer')).getText(); const message = parent.element(by.tagName('app-countdown-timer')).getText();
browser.sleep(10); // give `seconds` a chance to catchup with `message` browser.sleep(10); // give `seconds` a chance to catchup with `message`
let seconds = parent.element(by.className('seconds')).getText(); const seconds = parent.element(by.className('seconds')).getText();
expect(message).toContain(seconds); expect(message).toContain(seconds);
}); });
it('should stop the countdown', () => { it('should stop the countdown', () => {
let parent = element(by.tagName(parentTag)); const parent = element(by.tagName(parentTag));
let stopButton = parent.all(by.tagName('button')).get(1); const stopButton = parent.all(by.tagName('button')).get(1);
stopButton.click().then(() => { stopButton.click().then(() => {
let message = parent.element(by.tagName('app-countdown-timer')).getText(); const message = parent.element(by.tagName('app-countdown-timer')).getText();
expect(message).toContain('Holding'); expect(message).toContain('Holding');
}); });
}); });
@ -192,10 +192,10 @@ describe('Component Communication Cookbook Tests', () => {
// #docregion bidirectional-service // #docregion bidirectional-service
// ... // ...
it('should announce a mission', () => { it('should announce a mission', () => {
let missionControl = element(by.tagName('app-mission-control')); const missionControl = element(by.tagName('app-mission-control'));
let announceButton = missionControl.all(by.tagName('button')).get(0); const announceButton = missionControl.all(by.tagName('button')).get(0);
announceButton.click().then(() => { announceButton.click().then(() => {
let history = missionControl.all(by.tagName('li')); const history = missionControl.all(by.tagName('li'));
expect(history.count()).toBe(1); expect(history.count()).toBe(1);
expect(history.get(0).getText()).toMatch(/Mission.* announced/); expect(history.get(0).getText()).toMatch(/Mission.* announced/);
}); });
@ -214,11 +214,11 @@ describe('Component Communication Cookbook Tests', () => {
}); });
function testConfirmMission(buttonIndex: number, expectedLogCount: number, astronaut: string) { function testConfirmMission(buttonIndex: number, expectedLogCount: number, astronaut: string) {
let confirmedLog = ' confirmed the mission'; const confirmedLog = ' confirmed the mission';
let missionControl = element(by.tagName('app-mission-control')); const missionControl = element(by.tagName('app-mission-control'));
let confirmButton = missionControl.all(by.tagName('button')).get(buttonIndex); const confirmButton = missionControl.all(by.tagName('button')).get(buttonIndex);
confirmButton.click().then(() => { confirmButton.click().then(() => {
let history = missionControl.all(by.tagName('li')); const history = missionControl.all(by.tagName('li'));
expect(history.count()).toBe(expectedLogCount); expect(history.count()).toBe(expectedLogCount);
expect(history.get(expectedLogCount - 1).getText()).toBe(astronaut + confirmedLog); expect(history.get(expectedLogCount - 1).getText()).toBe(astronaut + confirmedLog);
}); });

View File

@ -15,7 +15,7 @@ import { VersionParentComponent } from './version-parent.component';
import { VoterComponent } from './voter.component'; import { VoterComponent } from './voter.component';
import { VoteTakerComponent } from './votetaker.component'; import { VoteTakerComponent } from './votetaker.component';
let directives: any[] = [ const directives: any[] = [
AppComponent, AppComponent,
AstronautComponent, AstronautComponent,
CountdownTimerComponent, CountdownTimerComponent,
@ -30,7 +30,7 @@ let directives: any[] = [
VoteTakerComponent VoteTakerComponent
]; ];
let schemas: any[] = []; const schemas: any[] = [];
// Include Countdown examples // Include Countdown examples
// unless in e2e tests which they break. // unless in e2e tests which they break.

View File

@ -34,7 +34,7 @@ export class MissionControlComponent {
} }
announce() { announce() {
let mission = this.missions[this.nextMission++]; const mission = this.missions[this.nextMission++];
this.missionService.announceMission(mission); this.missionService.announceMission(mission);
this.history.push(`Mission "${mission}" announced`); this.history.push(`Mission "${mission}" announced`);
if (this.nextMission >= this.missions.length) { this.nextMission = 0; } if (this.nextMission >= this.missions.length) { this.nextMission = 0; }

View File

@ -18,14 +18,14 @@ export class VersionChildComponent implements OnChanges {
changeLog: string[] = []; changeLog: string[] = [];
ngOnChanges(changes: {[propKey: string]: SimpleChange}) { ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
let log: string[] = []; const log: string[] = [];
for (let propName in changes) { for (const propName in changes) {
let changedProp = changes[propName]; const changedProp = changes[propName];
let to = JSON.stringify(changedProp.currentValue); const to = JSON.stringify(changedProp.currentValue);
if (changedProp.isFirstChange()) { if (changedProp.isFirstChange()) {
log.push(`Initial value of ${propName} set to ${to}`); log.push(`Initial value of ${propName} set to ${to}`);
} else { } else {
let from = JSON.stringify(changedProp.previousValue); const from = JSON.stringify(changedProp.previousValue);
log.push(`${propName} changed from ${from} to ${to}`); log.push(`${propName} changed from ${from} to ${to}`);
} }
} }

View File

@ -7,8 +7,8 @@ describe('Component Style Tests', () => {
}); });
it('scopes component styles to component view', () => { it('scopes component styles to component view', () => {
let componentH1 = element(by.css('app-root > h1')); const componentH1 = element(by.css('app-root > h1'));
let externalH1 = element(by.css('body > h1')); const externalH1 = element(by.css('body > h1'));
// Note: sometimes webdriver returns the fontWeight as "normal", // Note: sometimes webdriver returns the fontWeight as "normal",
// other times as "400", both of which are equal in CSS terms. // other times as "400", both of which are equal in CSS terms.
@ -18,48 +18,48 @@ describe('Component Style Tests', () => {
it('allows styling :host element', () => { it('allows styling :host element', () => {
let host = element(by.css('app-hero-details')); const host = element(by.css('app-hero-details'));
expect(host.getCssValue('borderWidth')).toEqual('1px'); expect(host.getCssValue('borderWidth')).toEqual('1px');
}); });
it('supports :host() in function form', () => { it('supports :host() in function form', () => {
let host = element(by.css('app-hero-details')); const host = element(by.css('app-hero-details'));
host.element(by.buttonText('Activate')).click(); host.element(by.buttonText('Activate')).click();
expect(host.getCssValue('borderWidth')).toEqual('3px'); expect(host.getCssValue('borderWidth')).toEqual('3px');
}); });
it('allows conditional :host-context() styling', () => { it('allows conditional :host-context() styling', () => {
let h2 = element(by.css('app-hero-details h2')); const h2 = element(by.css('app-hero-details h2'));
expect(h2.getCssValue('backgroundColor')).toEqual('rgba(238, 238, 255, 1)'); // #eeeeff expect(h2.getCssValue('backgroundColor')).toEqual('rgba(238, 238, 255, 1)'); // #eeeeff
}); });
it('styles both view and content children with /deep/', () => { it('styles both view and content children with /deep/', () => {
let viewH3 = element(by.css('app-hero-team h3')); const viewH3 = element(by.css('app-hero-team h3'));
let contentH3 = element(by.css('app-hero-controls h3')); const contentH3 = element(by.css('app-hero-controls h3'));
expect(viewH3.getCssValue('fontStyle')).toEqual('italic'); expect(viewH3.getCssValue('fontStyle')).toEqual('italic');
expect(contentH3.getCssValue('fontStyle')).toEqual('italic'); expect(contentH3.getCssValue('fontStyle')).toEqual('italic');
}); });
it('includes styles loaded with CSS @import', () => { it('includes styles loaded with CSS @import', () => {
let host = element(by.css('app-hero-details')); const host = element(by.css('app-hero-details'));
expect(host.getCssValue('padding')).toEqual('10px'); expect(host.getCssValue('padding')).toEqual('10px');
}); });
it('processes template inline styles', () => { it('processes template inline styles', () => {
let button = element(by.css('app-hero-controls button')); const button = element(by.css('app-hero-controls button'));
let externalButton = element(by.css('body > button')); const externalButton = element(by.css('body > button'));
expect(button.getCssValue('backgroundColor')).toEqual('rgba(255, 255, 255, 1)'); // #ffffff expect(button.getCssValue('backgroundColor')).toEqual('rgba(255, 255, 255, 1)'); // #ffffff
expect(externalButton.getCssValue('backgroundColor')).not.toEqual('rgba(255, 255, 255, 1)'); expect(externalButton.getCssValue('backgroundColor')).not.toEqual('rgba(255, 255, 255, 1)');
}); });
it('processes template <link>s', () => { it('processes template <link>s', () => {
let li = element(by.css('app-hero-team li:first-child')); const li = element(by.css('app-hero-team li:first-child'));
let externalLi = element(by.css('body > ul li')); const externalLi = element(by.css('body > ul li'));
expect(li.getCssValue('listStyleType')).toEqual('square'); expect(li.getCssValue('listStyleType')).toEqual('square');
expect(externalLi.getCssValue('listStyleType')).not.toEqual('square'); expect(externalLi.getCssValue('listStyleType')).not.toEqual('square');

View File

@ -7,68 +7,68 @@ describe('Dependency Injection Cookbook', () => {
}); });
it('should render Logged in User example', () => { it('should render Logged in User example', () => {
let loggedInUser = element.all(by.xpath('//h3[text()="Logged in user"]')).get(0); const loggedInUser = element.all(by.xpath('//h3[text()="Logged in user"]')).get(0);
expect(loggedInUser).toBeDefined(); expect(loggedInUser).toBeDefined();
}); });
it('"Bombasto" should be the logged in user', () => { it('"Bombasto" should be the logged in user', () => {
let loggedInUser = element.all(by.xpath('//div[text()="Name: Bombasto"]')).get(0); const loggedInUser = element.all(by.xpath('//div[text()="Name: Bombasto"]')).get(0);
expect(loggedInUser).toBeDefined(); expect(loggedInUser).toBeDefined();
}); });
it('should render sorted heroes', () => { it('should render sorted heroes', () => {
let sortedHeroes = element.all(by.xpath('//h3[text()="Sorted Heroes" and position()=1]')).get(0); const sortedHeroes = element.all(by.xpath('//h3[text()="Sorted Heroes" and position()=1]')).get(0);
expect(sortedHeroes).toBeDefined(); expect(sortedHeroes).toBeDefined();
}); });
it('Dr Nice should be in sorted heroes', () => { it('Dr Nice should be in sorted heroes', () => {
let sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Dr Nice" and position()=2]')).get(0); const sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Dr Nice" and position()=2]')).get(0);
expect(sortedHero).toBeDefined(); expect(sortedHero).toBeDefined();
}); });
it('RubberMan should be in sorted heroes', () => { it('RubberMan should be in sorted heroes', () => {
let sortedHero = element.all(by.xpath('//sorted-heroes/[text()="RubberMan" and position()=3]')).get(0); const sortedHero = element.all(by.xpath('//sorted-heroes/[text()="RubberMan" and position()=3]')).get(0);
expect(sortedHero).toBeDefined(); expect(sortedHero).toBeDefined();
}); });
it('Magma should be in sorted heroes', () => { it('Magma should be in sorted heroes', () => {
let sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Magma"]')).get(0); const sortedHero = element.all(by.xpath('//sorted-heroes/[text()="Magma"]')).get(0);
expect(sortedHero).toBeDefined(); expect(sortedHero).toBeDefined();
}); });
it('should render Hero of the Month', () => { it('should render Hero of the Month', () => {
let heroOfTheMonth = element.all(by.xpath('//h3[text()="Hero of the month"]')).get(0); const heroOfTheMonth = element.all(by.xpath('//h3[text()="Hero of the month"]')).get(0);
expect(heroOfTheMonth).toBeDefined(); expect(heroOfTheMonth).toBeDefined();
}); });
it('should render Hero Bios', () => { it('should render Hero Bios', () => {
let heroBios = element.all(by.xpath('//h3[text()="Hero Bios"]')).get(0); const heroBios = element.all(by.xpath('//h3[text()="Hero Bios"]')).get(0);
expect(heroBios).toBeDefined(); expect(heroBios).toBeDefined();
}); });
it('should render Magma\'s description in Hero Bios', () => { it('should render Magma\'s description in Hero Bios', () => {
let magmaText = element.all(by.xpath('//textarea[text()="Hero of all trades"]')).get(0); const magmaText = element.all(by.xpath('//textarea[text()="Hero of all trades"]')).get(0);
expect(magmaText).toBeDefined(); expect(magmaText).toBeDefined();
}); });
it('should render Magma\'s phone in Hero Bios and Contacts', () => { it('should render Magma\'s phone in Hero Bios and Contacts', () => {
let magmaPhone = element.all(by.xpath('//div[text()="Phone #: 555-555-5555"]')).get(0); const magmaPhone = element.all(by.xpath('//div[text()="Phone #: 555-555-5555"]')).get(0);
expect(magmaPhone).toBeDefined(); expect(magmaPhone).toBeDefined();
}); });
it('should render Hero-of-the-Month runner-ups', () => { it('should render Hero-of-the-Month runner-ups', () => {
let runnersUp = element(by.id('rups1')).getText(); const runnersUp = element(by.id('rups1')).getText();
expect(runnersUp).toContain('RubberMan, Dr Nice'); expect(runnersUp).toContain('RubberMan, Dr Nice');
}); });
it('should render DateLogger log entry in Hero-of-the-Month', () => { it('should render DateLogger log entry in Hero-of-the-Month', () => {
let logs = element.all(by.id('logs')).get(0).getText(); const logs = element.all(by.id('logs')).get(0).getText();
expect(logs).toContain('INFO: starting up at'); expect(logs).toContain('INFO: starting up at');
}); });
it('should highlight Hero Bios and Contacts container when mouseover', () => { it('should highlight Hero Bios and Contacts container when mouseover', () => {
let target = element(by.css('div[appHighlight="yellow"]')); const target = element(by.css('div[appHighlight="yellow"]'));
let yellow = 'rgba(255, 255, 0, 1)'; const yellow = 'rgba(255, 255, 0, 1)';
expect(target.getCssValue('background-color')).not.toEqual(yellow); expect(target.getCssValue('background-color')).not.toEqual(yellow);
@ -80,10 +80,10 @@ describe('Dependency Injection Cookbook', () => {
}); });
describe('in Parent Finder', () => { describe('in Parent Finder', () => {
let cathy1 = element(by.css('alex cathy')); const cathy1 = element(by.css('alex cathy'));
let craig1 = element(by.css('alex craig')); const craig1 = element(by.css('alex craig'));
let carol1 = element(by.css('alex carol p')); const carol1 = element(by.css('alex carol p'));
let carol2 = element(by.css('barry carol p')); const carol2 = element(by.css('barry carol p'));
it('"Cathy" should find "Alex" via the component class', () => { it('"Cathy" should find "Alex" via the component class', () => {
expect(cathy1.getText()).toContain('Found Alex via the component'); expect(cathy1.getText()).toContain('Found Alex via the component');

View File

@ -3,7 +3,7 @@ import { Hero } from './hero';
export class HeroData { export class HeroData {
createDb() { createDb() {
let heroes = [ const heroes = [
new Hero(1, 'Windstorm'), new Hero(1, 'Windstorm'),
new Hero(2, 'Bombasto'), new Hero(2, 'Bombasto'),
new Hero(3, 'Magneta'), new Hero(3, 'Magneta'),

View File

@ -24,7 +24,7 @@ export class UserContextService {
// #enddocregion ctor, injectables // #enddocregion ctor, injectables
loadUser(userId: number) { loadUser(userId: number) {
let user = this.userService.getUserById(userId); const user = this.userService.getUserById(userId);
this.name = user.name; this.name = user.name;
this.role = user.role; this.role = user.role;

View File

@ -138,15 +138,15 @@ describe('Dependency Injection Tests', () => {
}); });
it('unauthorized user should have multiple unauthorized heroes', () => { it('unauthorized user should have multiple unauthorized heroes', () => {
let heroes = element.all(by.css('#unauthorized app-hero-list div')); const heroes = element.all(by.css('#unauthorized app-hero-list div'));
expect(heroes.count()).toBeGreaterThan(0); expect(heroes.count()).toBeGreaterThan(0);
}); });
it('unauthorized user should have no secret heroes', () => { it('unauthorized user should have no secret heroes', () => {
let heroes = element.all(by.css('#unauthorized app-hero-list div')); const heroes = element.all(by.css('#unauthorized app-hero-list div'));
expect(heroes.count()).toBeGreaterThan(0); expect(heroes.count()).toBeGreaterThan(0);
let filteredHeroes = heroes.filter((elem: ElementFinder, index: number) => { const filteredHeroes = heroes.filter((elem: ElementFinder, index: number) => {
return elem.getText().then((text: string) => /secret/.test(text)); return elem.getText().then((text: string) => /secret/.test(text));
}); });
@ -160,7 +160,7 @@ describe('Dependency Injection Tests', () => {
describe('after button click', () => { describe('after button click', () => {
beforeAll((done: any) => { beforeAll((done: any) => {
let buttonEle = element.all(by.cssContainingText('button', 'Next User')).get(0); const buttonEle = element.all(by.cssContainingText('button', 'Next User')).get(0);
buttonEle.click().then(done, done); buttonEle.click().then(done, done);
}); });
@ -170,20 +170,20 @@ describe('Dependency Injection Tests', () => {
}); });
it('authorized user should have multiple authorized heroes ', () => { it('authorized user should have multiple authorized heroes ', () => {
let heroes = element.all(by.css('#authorized app-hero-list div')); const heroes = element.all(by.css('#authorized app-hero-list div'));
expect(heroes.count()).toBeGreaterThan(0); expect(heroes.count()).toBeGreaterThan(0);
}); });
it('authorized user should have multiple authorized heroes with tree-shakeable HeroesService', () => { it('authorized user should have multiple authorized heroes with tree-shakeable HeroesService', () => {
let heroes = element.all(by.css('#tspAuthorized app-hero-list div')); const heroes = element.all(by.css('#tspAuthorized app-hero-list div'));
expect(heroes.count()).toBeGreaterThan(0); expect(heroes.count()).toBeGreaterThan(0);
}); });
it('authorized user should have secret heroes', () => { it('authorized user should have secret heroes', () => {
let heroes = element.all(by.css('#authorized app-hero-list div')); const heroes = element.all(by.css('#authorized app-hero-list div'));
expect(heroes.count()).toBeGreaterThan(0); expect(heroes.count()).toBeGreaterThan(0);
let filteredHeroes = heroes.filter((elem: ElementFinder, index: number) => { const filteredHeroes = heroes.filter((elem: ElementFinder, index: number) => {
return elem.getText().then((text: string) => /secret/.test(text)); return elem.getText().then((text: string) => /secret/.test(text));
}); });

View File

@ -7,7 +7,7 @@ import { Car, Engine, Tires } from './car';
export function simpleCar() { export function simpleCar() {
// #docregion car-ctor-instantiation // #docregion car-ctor-instantiation
// Simple car with 4 cylinders and Flintstone tires. // Simple car with 4 cylinders and Flintstone tires.
let car = new Car(new Engine(), new Tires()); const car = new Car(new Engine(), new Tires());
// #enddocregion car-ctor-instantiation // #enddocregion car-ctor-instantiation
car.description = 'Simple'; car.description = 'Simple';
return car; return car;
@ -24,8 +24,8 @@ class Engine2 {
export function superCar() { export function superCar() {
// #docregion car-ctor-instantiation-with-param // #docregion car-ctor-instantiation-with-param
// Super car with 12 cylinders and Flintstone tires. // Super car with 12 cylinders and Flintstone tires.
let bigCylinders = 12; const bigCylinders = 12;
let car = new Car(new Engine2(bigCylinders), new Tires()); const car = new Car(new Engine2(bigCylinders), new Tires());
// #enddocregion car-ctor-instantiation-with-param // #enddocregion car-ctor-instantiation-with-param
car.description = 'Super'; car.description = 'Super';
return car; return car;
@ -40,7 +40,7 @@ class MockTires extends Tires { make = 'YokoGoodStone'; }
export function testCar() { export function testCar() {
// #docregion car-ctor-instantiation-with-mocks // #docregion car-ctor-instantiation-with-mocks
// Test car with 8 cylinders and YokoGoodStone tires. // Test car with 8 cylinders and YokoGoodStone tires.
let car = new Car(new MockEngine(), new MockTires()); const car = new Car(new MockEngine(), new MockTires());
// #enddocregion car-ctor-instantiation-with-mocks // #enddocregion car-ctor-instantiation-with-mocks
car.description = 'Test'; car.description = 'Test';
return car; return car;

View File

@ -4,7 +4,7 @@ import { Engine, Tires, Car } from './car';
// BAD pattern! // BAD pattern!
export class CarFactory { export class CarFactory {
createCar() { createCar() {
let car = new Car(this.createEngine(), this.createTires()); const car = new Car(this.createEngine(), this.createTires());
car.description = 'Factory'; car.description = 'Factory';
return car; return car;
} }

View File

@ -26,14 +26,14 @@ export function useInjector() {
] ]
}); });
// #docregion injector-call // #docregion injector-call
let car = injector.get(Car); const car = injector.get(Car);
// #enddocregion injector-call, injector-create-and-call // #enddocregion injector-call, injector-create-and-call
car.description = 'Injector'; car.description = 'Injector';
injector = Injector.create({ injector = Injector.create({
providers: [{ provide: Logger, deps: [] }] providers: [{ provide: Logger, deps: [] }]
}); });
let logger = injector.get(Logger); const logger = injector.get(Logger);
logger.log('Injector car.drive() said: ' + car.drive()); logger.log('Injector car.drive() said: ' + car.drive());
return car; return car;
} }

View File

@ -5,7 +5,7 @@ import { Logger } from '../logger.service';
import { UserService } from '../user.service'; import { UserService } from '../user.service';
// #docregion factory // #docregion factory
let heroServiceFactory = (logger: Logger, userService: UserService) => { const heroServiceFactory = (logger: Logger, userService: UserService) => {
return new HeroService(logger, userService.user.isAuthorized); return new HeroService(logger, userService.user.isAuthorized);
}; };
// #enddocregion factory // #enddocregion factory

View File

@ -17,7 +17,7 @@ export class HeroService {
private isAuthorized: boolean) { } private isAuthorized: boolean) { }
getHeroes() { getHeroes() {
let auth = this.isAuthorized ? 'authorized ' : 'unauthorized'; const auth = this.isAuthorized ? 'authorized ' : 'unauthorized';
this.logger.log(`Getting heroes for ${auth} user.`); this.logger.log(`Getting heroes for ${auth} user.`);
return HEROES.filter(hero => this.isAuthorized || !hero.isSecret); return HEROES.filter(hero => this.isAuthorized || !hero.isSecret);
} }

View File

@ -36,7 +36,7 @@ export class InjectorComponent implements OnInit {
} }
get rodent() { get rodent() {
let rousDontExist = `R.O.U.S.'s? I don't think they exist!`; const rousDontExist = `R.O.U.S.'s? I don't think they exist!`;
return this.injector.get(ROUS, rousDontExist); return this.injector.get(ROUS, rousDontExist);
} }
} }

View File

@ -76,7 +76,7 @@ export class EvenBetterLogger extends Logger {
constructor(private userService: UserService) { super(); } constructor(private userService: UserService) { super(); }
log(message: string) { log(message: string) {
let name = this.userService.user.name; const name = this.userService.user.name;
super.log(`Message to ${name}: ${message}`); super.log(`Message to ${name}: ${message}`);
} }
} }
@ -237,7 +237,7 @@ export class Provider9Component implements OnInit {
import { Optional } from '@angular/core'; import { Optional } from '@angular/core';
// #enddocregion import-optional // #enddocregion import-optional
let someMessage = 'Hello from the injected logger'; const someMessage = 'Hello from the injected logger';
@Component({ @Component({
selector: 'provider-10', selector: 'provider-10',

View File

@ -8,8 +8,8 @@ export class User {
} }
// TODO: get the user; don't 'new' it. // TODO: get the user; don't 'new' it.
let alice = new User('Alice', true); const alice = new User('Alice', true);
let bob = new User('Bob', false); const bob = new User('Bob', false);
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'

View File

@ -1,8 +1,8 @@
import { browser, element, by } from 'protractor'; import { browser, element, by } from 'protractor';
describe('Displaying Data Tests', () => { describe('Displaying Data Tests', () => {
let title = 'Tour of Heroes'; const title = 'Tour of Heroes';
let defaultHero = 'Windstorm'; const defaultHero = 'Windstorm';
beforeAll(() => { beforeAll(() => {
browser.get(''); browser.get('');
@ -17,7 +17,7 @@ describe('Displaying Data Tests', () => {
}); });
it('should have heroes', () => { it('should have heroes', () => {
let heroEls = element.all(by.css('li')); const heroEls = element.all(by.css('li'));
expect(heroEls.count()).not.toBe(0, 'should have heroes'); expect(heroEls.count()).not.toBe(0, 'should have heroes');
}); });

View File

@ -1,7 +1,7 @@
import { browser, element, by } from 'protractor'; import { browser, element, by } from 'protractor';
describe('Docs Style Guide', () => { describe('Docs Style Guide', () => {
let title = 'Authors Style Guide Sample'; const title = 'Authors Style Guide Sample';
beforeAll(() => { beforeAll(() => {
browser.get(''); browser.get('');

View File

@ -8,9 +8,9 @@ describe('Dynamic Component Loader', () => {
}); });
it('should load ad banner', () => { it('should load ad banner', () => {
let headline = element(by.xpath("//h4[text()='Featured Hero Profile']")); const headline = element(by.xpath("//h4[text()='Featured Hero Profile']"));
let name = element(by.xpath("//h3[text()='Bombasto']")); const name = element(by.xpath("//h3[text()='Bombasto']"));
let bio = element(by.xpath("//p[text()='Brave as they come']")); const bio = element(by.xpath("//p[text()='Brave as they come']"));
expect(name).toBeDefined(); expect(name).toBeDefined();
expect(headline).toBeDefined(); expect(headline).toBeDefined();

View File

@ -8,17 +8,17 @@ describe('Dynamic Form', () => {
}); });
it('should submit form', () => { it('should submit form', () => {
let firstNameElement = element.all(by.css('input[id=firstName]')).get(0); const firstNameElement = element.all(by.css('input[id=firstName]')).get(0);
expect(firstNameElement.getAttribute('value')).toEqual('Bombasto'); expect(firstNameElement.getAttribute('value')).toEqual('Bombasto');
let emailElement = element.all(by.css('input[id=emailAddress]')).get(0); const emailElement = element.all(by.css('input[id=emailAddress]')).get(0);
let email = 'test@test.com'; const email = 'test@test.com';
emailElement.sendKeys(email); emailElement.sendKeys(email);
expect(emailElement.getAttribute('value')).toEqual(email); expect(emailElement.getAttribute('value')).toEqual(email);
element(by.css('select option[value="solid"]')).click(); element(by.css('select option[value="solid"]')).click();
let saveButton = element.all(by.css('button')).get(0); const saveButton = element.all(by.css('button')).get(0);
saveButton.click().then(() => { saveButton.click().then(() => {
expect(element(by.xpath("//strong[contains(text(),'Saved the following values')]")).isPresent()).toBe(true); expect(element(by.xpath("//strong[contains(text(),'Saved the following values')]")).isPresent()).toBe(true);
}); });

View File

@ -9,7 +9,7 @@ export class QuestionControlService {
constructor() { } constructor() { }
toFormGroup(questions: QuestionBase<string>[] ) { toFormGroup(questions: QuestionBase<string>[] ) {
let group: any = {}; const group: any = {};
questions.forEach(question => { questions.forEach(question => {
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required) group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)

View File

@ -12,7 +12,7 @@ export class QuestionService {
// TODO: get from a remote source of question metadata // TODO: get from a remote source of question metadata
getQuestions() { getQuestions() {
let questions: QuestionBase<string>[] = [ const questions: QuestionBase<string>[] = [
new DropdownQuestion({ new DropdownQuestion({
key: 'brave', key: 'brave',

View File

@ -6,12 +6,12 @@ describe('Event binding example', () => {
browser.get(''); browser.get('');
}); });
let saveButton = element.all(by.css('button')).get(0); const saveButton = element.all(by.css('button')).get(0);
let onSaveButton = element.all(by.css('button')).get(1); const onSaveButton = element.all(by.css('button')).get(1);
let myClick = element.all(by.css('button')).get(2); const myClick = element.all(by.css('button')).get(2);
let deleteButton = element.all(by.css('button')).get(3); const deleteButton = element.all(by.css('button')).get(3);
let saveNoProp = element.all(by.css('button')).get(4); const saveNoProp = element.all(by.css('button')).get(4);
let saveProp = element.all(by.css('button')).get(5); const saveProp = element.all(by.css('button')).get(5);
it('should display Event Binding with Angular', () => { it('should display Event Binding with Angular', () => {
@ -28,8 +28,8 @@ describe('Event binding example', () => {
}); });
it('should support user input', () => { it('should support user input', () => {
let input = element(by.css('input')); const input = element(by.css('input'));
let bindingResult = element.all(by.css('h4')).get(1); const bindingResult = element.all(by.css('h4')).get(1);
expect(bindingResult.getText()).toEqual('Result: teapot'); expect(bindingResult.getText()).toEqual('Result: teapot');
input.sendKeys('abc'); input.sendKeys('abc');
expect(bindingResult.getText()).toEqual('Result: teapotabc'); expect(bindingResult.getText()).toEqual('Result: teapotabc');
@ -42,8 +42,8 @@ describe('Event binding example', () => {
}); });
it('should show two alerts', async () => { it('should show two alerts', async () => {
let parentDiv = element.all(by.css('.parent-div')); const parentDiv = element.all(by.css('.parent-div'));
let childDiv = element.all(by.css('div > div')).get(1); const childDiv = element.all(by.css('div > div')).get(1);
await parentDiv.click(); await parentDiv.click();
browser.switchTo().alert().accept(); browser.switchTo().alert().accept();
expect(childDiv.getText()).toEqual('Click me too! (child)'); expect(childDiv.getText()).toEqual('Click me too! (child)');

View File

@ -50,8 +50,8 @@ let page: {
}; };
function getPage(sectionTag: string) { function getPage(sectionTag: string) {
let section = element(by.css(sectionTag)); const section = element(by.css(sectionTag));
let buttons = section.all(by.css('button')); const buttons = section.all(by.css('button'));
page = { page = {
section, section,

View File

@ -1,5 +1,5 @@
export function createNewEvent(eventName: string, bubbles = false, cancelable = false) { export function createNewEvent(eventName: string, bubbles = false, cancelable = false) {
let evt = document.createEvent('CustomEvent'); const evt = document.createEvent('CustomEvent');
evt.initCustomEvent(eventName, bubbles, cancelable, null); evt.initCustomEvent(eventName, bubbles, cancelable, null);
return evt; return evt;
} }

View File

@ -12,49 +12,49 @@ describe('Forms Tests', () => {
it('should not display message before submit', () => { it('should not display message before submit', () => {
let ele = element(by.css('h2')); const ele = element(by.css('h2'));
expect(ele.isDisplayed()).toBe(false); expect(ele.isDisplayed()).toBe(false);
}); });
it('should hide form after submit', () => { it('should hide form after submit', () => {
let ele = element.all(by.css('h1')).get(0); const ele = element.all(by.css('h1')).get(0);
expect(ele.isDisplayed()).toBe(true); expect(ele.isDisplayed()).toBe(true);
let b = element.all(by.css('button[type=submit]')).get(0); const b = element.all(by.css('button[type=submit]')).get(0);
b.click().then(() => { b.click().then(() => {
expect(ele.isDisplayed()).toBe(false); expect(ele.isDisplayed()).toBe(false);
}); });
}); });
it('should display message after submit', () => { it('should display message after submit', () => {
let b = element.all(by.css('button[type=submit]')).get(0); const b = element.all(by.css('button[type=submit]')).get(0);
b.click().then(() => { b.click().then(() => {
expect(element(by.css('h2')).getText()).toContain('You submitted the following'); expect(element(by.css('h2')).getText()).toContain('You submitted the following');
}); });
}); });
it('should hide form after submit', () => { it('should hide form after submit', () => {
let alterEgoEle = element.all(by.css('input[name=alterEgo]')).get(0); const alterEgoEle = element.all(by.css('input[name=alterEgo]')).get(0);
expect(alterEgoEle.isDisplayed()).toBe(true); expect(alterEgoEle.isDisplayed()).toBe(true);
let submitButtonEle = element.all(by.css('button[type=submit]')).get(0); const submitButtonEle = element.all(by.css('button[type=submit]')).get(0);
submitButtonEle.click().then(() => { submitButtonEle.click().then(() => {
expect(alterEgoEle.isDisplayed()).toBe(false); expect(alterEgoEle.isDisplayed()).toBe(false);
}); });
}); });
it('should reflect submitted data after submit', () => { it('should reflect submitted data after submit', () => {
let test = 'testing 1 2 3'; const test = 'testing 1 2 3';
let newValue: string; let newValue: string;
let alterEgoEle = element.all(by.css('input[name=alterEgo]')).get(0); const alterEgoEle = element.all(by.css('input[name=alterEgo]')).get(0);
alterEgoEle.getAttribute('value').then((value: string) => { alterEgoEle.getAttribute('value').then((value: string) => {
alterEgoEle.sendKeys(test); alterEgoEle.sendKeys(test);
newValue = value + test; newValue = value + test;
expect(alterEgoEle.getAttribute('value')).toEqual(newValue); expect(alterEgoEle.getAttribute('value')).toEqual(newValue);
let b = element.all(by.css('button[type=submit]')).get(0); const b = element.all(by.css('button[type=submit]')).get(0);
return b.click(); return b.click();
}).then(() => { }).then(() => {
let alterEgoTextEle = element(by.cssContainingText('div', 'Alter Ego')); const alterEgoTextEle = element(by.cssContainingText('div', 'Alter Ego'));
expect(alterEgoTextEle.isPresent()).toBe(true, 'cannot locate "Alter Ego" label'); expect(alterEgoTextEle.isPresent()).toBe(true, 'cannot locate "Alter Ego" label');
let divEle = element(by.cssContainingText('div', newValue)); const divEle = element(by.cssContainingText('div', newValue));
expect(divEle.isPresent()).toBe(true, 'cannot locate div with this text: ' + newValue); expect(divEle.isPresent()).toBe(true, 'cannot locate div with this text: ' + newValue);
}); });
}); });

View File

@ -35,7 +35,7 @@ export class HeroFormComponent {
skyDog(): Hero { skyDog(): Hero {
// #docregion SkyDog // #docregion SkyDog
let myHero = new Hero(42, 'SkyDog', const myHero = new Hero(42, 'SkyDog',
'Fetch any object at any distance', 'Fetch any object at any distance',
'Leslie Rollover'); 'Leslie Rollover');
console.log('My hero is called ' + myHero.name); // "My hero is called SkyDog" console.log('My hero is called ' + myHero.name); // "My hero is called SkyDog"

View File

@ -7,7 +7,7 @@ describe('Hierarchical dependency injection', () => {
}); });
describe('Heroes Scenario', () => { describe('Heroes Scenario', () => {
let page = { const page = {
heroName: '', heroName: '',
income: '', income: '',

View File

@ -24,7 +24,7 @@ const page = {
uploadMessage: element(by.css('app-uploader p')) uploadMessage: element(by.css('app-uploader p'))
}; };
let checkLogForMessage = (message: string) => { const checkLogForMessage = (message: string) => {
expect(page.logList.getText()).toContain(message); expect(page.logList.getText()).toContain(message);
}; };

View File

@ -90,7 +90,7 @@ describe('HttpClient testing', () => {
}); });
it('can test multiple requests', () => { it('can test multiple requests', () => {
let testData: Data[] = [ const testData: Data[] = [
{ name: 'bob' }, { name: 'carol' }, { name: 'bob' }, { name: 'carol' },
{ name: 'ted' }, { name: 'alice' } { name: 'ted' }, { name: 'alice' }
]; ];

View File

@ -18,43 +18,43 @@ describe('Inputs and Outputs', () => {
} }
it('should have title Inputs and Outputs', () => { it('should have title Inputs and Outputs', () => {
let title = element.all(by.css('h1')).get(0); const title = element.all(by.css('h1')).get(0);
expect(title.getText()).toEqual('Inputs and Outputs'); expect(title.getText()).toEqual('Inputs and Outputs');
}); });
it('should add 123 to the parent list', async () => { it('should add 123 to the parent list', async () => {
let addToParentButton = element.all(by.css('button')).get(0); const addToParentButton = element.all(by.css('button')).get(0);
let addToListInput = element.all(by.css('input')).get(0); const addToListInput = element.all(by.css('input')).get(0);
let addedItem = element.all(by.css('li')).get(4); const addedItem = element.all(by.css('li')).get(4);
await addToListInput.sendKeys('123'); await addToListInput.sendKeys('123');
await addToParentButton.click(); await addToParentButton.click();
expect(addedItem.getText()).toEqual('123'); expect(addedItem.getText()).toEqual('123');
}); });
it('should delete item', async () => { it('should delete item', async () => {
let deleteButton = element.all(by.css('button')).get(1); const deleteButton = element.all(by.css('button')).get(1);
const contents = 'Child'; const contents = 'Child';
await deleteButton.click(); await deleteButton.click();
await logChecker(deleteButton, contents); await logChecker(deleteButton, contents);
}); });
it('should log buy the item', async () => { it('should log buy the item', async () => {
let buyButton = element.all(by.css('button')).get(2); const buyButton = element.all(by.css('button')).get(2);
const contents = 'Child'; const contents = 'Child';
await buyButton.click(); await buyButton.click();
await logChecker(buyButton, contents); await logChecker(buyButton, contents);
}); });
it('should save item for later', async () => { it('should save item for later', async () => {
let saveButton = element.all(by.css('button')).get(3); const saveButton = element.all(by.css('button')).get(3);
const contents = 'Child'; const contents = 'Child';
await saveButton.click(); await saveButton.click();
await logChecker(saveButton, contents); await logChecker(saveButton, contents);
}); });
it('should add item to wishlist', async () => { it('should add item to wishlist', async () => {
let addToParentButton = element.all(by.css('button')).get(4); const addToParentButton = element.all(by.css('button')).get(4);
let addedItem = element.all(by.css('li')).get(6); const addedItem = element.all(by.css('li')).get(6);
await addToParentButton.click(); await addToParentButton.click();
expect(addedItem.getText()).toEqual('Television'); expect(addedItem.getText()).toEqual('Television');
}); });

View File

@ -27,8 +27,8 @@ describe('Interpolation e2e tests', () => {
}); });
it('should display two pictures', () => { it('should display two pictures', () => {
let pottedPlant = element.all(by.css('img')).get(0); const pottedPlant = element.all(by.css('img')).get(0);
let lamp = element.all(by.css('img')).get(1); const lamp = element.all(by.css('img')).get(1);
expect(pottedPlant.getAttribute('src')).toContain('potted-plant'); expect(pottedPlant.getAttribute('src')).toContain('potted-plant');
expect(pottedPlant.isDisplayed()).toBe(true); expect(pottedPlant.isDisplayed()).toBe(true);
@ -38,8 +38,8 @@ describe('Interpolation e2e tests', () => {
}); });
it('should support user input', () => { it('should support user input', () => {
let input = element(by.css('input')); const input = element(by.css('input'));
let label = element(by.css('label')); const label = element(by.css('label'));
expect(label.getText()).toEqual('Type something:'); expect(label.getText()).toEqual('Type something:');
input.sendKeys('abc'); input.sendKeys('abc');
expect(label.getText()).toEqual('Type something: abc'); expect(label.getText()).toEqual('Type something: abc');

View File

@ -24,7 +24,7 @@ describe('providers App', () => {
}); });
it('should show customers when the button is clicked', () => { it('should show customers when the button is clicked', () => {
let customersMessage = element(by.css('app-customers > p')); const customersMessage = element(by.css('app-customers > p'));
expect(customersMessage.getText()).toBe('customers works!'); expect(customersMessage.getText()).toBe('customers works!');
}); });
@ -36,7 +36,7 @@ describe('providers App', () => {
}); });
it('should show orders when the button is clicked', () => { it('should show orders when the button is clicked', () => {
let ordersMessage = element(by.css('app-orders > p')); const ordersMessage = element(by.css('app-orders > p'));
expect(ordersMessage.getText()).toBe('orders works!'); expect(ordersMessage.getText()).toBe('orders works!');
}); });

View File

@ -13,11 +13,11 @@ describe('Lifecycle hooks', () => {
}); });
it('should support peek-a-boo', async () => { it('should support peek-a-boo', async () => {
let pabComp = element(by.css('peek-a-boo-parent peek-a-boo')); const pabComp = element(by.css('peek-a-boo-parent peek-a-boo'));
expect(pabComp.isPresent()).toBe(false, 'should not be able to find the "peek-a-boo" component'); expect(pabComp.isPresent()).toBe(false, 'should not be able to find the "peek-a-boo" component');
let pabButton = element.all(by.css('peek-a-boo-parent button')).get(0); const pabButton = element.all(by.css('peek-a-boo-parent button')).get(0);
let updateHeroButton = element.all(by.css('peek-a-boo-parent button')).get(1); const updateHeroButton = element.all(by.css('peek-a-boo-parent button')).get(1);
expect(pabButton.getText()).toContain('Create Peek'); expect(pabButton.getText()).toContain('Create Peek');
await pabButton.click(); await pabButton.click();
@ -35,12 +35,12 @@ describe('Lifecycle hooks', () => {
}); });
it('should support OnChanges hook', () => { it('should support OnChanges hook', () => {
let onChangesViewEle = element.all(by.css('on-changes div')).get(0); const onChangesViewEle = element.all(by.css('on-changes div')).get(0);
let inputEles = element.all(by.css('on-changes-parent input')); const inputEles = element.all(by.css('on-changes-parent input'));
let heroNameInputEle = inputEles.get(1); const heroNameInputEle = inputEles.get(1);
let powerInputEle = inputEles.get(0); const powerInputEle = inputEles.get(0);
let titleEle = onChangesViewEle.element(by.css('p')); const titleEle = onChangesViewEle.element(by.css('p'));
let changeLogEles = onChangesViewEle.all(by.css('div')); const changeLogEles = onChangesViewEle.all(by.css('div'));
expect(titleEle.getText()).toContain('Windstorm can sing'); expect(titleEle.getText()).toContain('Windstorm can sing');
expect(changeLogEles.count()).toEqual(2, 'should start with 2 messages'); expect(changeLogEles.count()).toEqual(2, 'should start with 2 messages');
@ -54,12 +54,12 @@ describe('Lifecycle hooks', () => {
}); });
it('should support DoCheck hook', async () => { it('should support DoCheck hook', async () => {
let doCheckViewEle = element.all(by.css('do-check div')).get(0); const doCheckViewEle = element.all(by.css('do-check div')).get(0);
let inputEles = element.all(by.css('do-check-parent input')); const inputEles = element.all(by.css('do-check-parent input'));
let heroNameInputEle = inputEles.get(1); const heroNameInputEle = inputEles.get(1);
let powerInputEle = inputEles.get(0); const powerInputEle = inputEles.get(0);
let titleEle = doCheckViewEle.element(by.css('p')); const titleEle = doCheckViewEle.element(by.css('p'));
let changeLogEles = doCheckViewEle.all(by.css('div')); const changeLogEles = doCheckViewEle.all(by.css('div'));
let logCount: number; let logCount: number;
expect(titleEle.getText()).toContain('Windstorm can sing'); expect(titleEle.getText()).toContain('Windstorm can sing');
@ -82,11 +82,11 @@ describe('Lifecycle hooks', () => {
}); });
it('should support AfterView hooks', async () => { it('should support AfterView hooks', async () => {
let parentEle = element(by.tagName('after-view-parent')); const parentEle = element(by.tagName('after-view-parent'));
let buttonEle = parentEle.element(by.tagName('button')); // Reset const buttonEle = parentEle.element(by.tagName('button')); // Reset
let commentEle = parentEle.element(by.className('comment')); const commentEle = parentEle.element(by.className('comment'));
let logEles = parentEle.all(by.css('h4 ~ div')); const logEles = parentEle.all(by.css('h4 ~ div'));
let childViewInputEle = parentEle.element(by.css('app-child-view input')); const childViewInputEle = parentEle.element(by.css('app-child-view input'));
let logCount: number; let logCount: number;
expect(childViewInputEle.getAttribute('value')).toContain('Magneta'); expect(childViewInputEle.getAttribute('value')).toContain('Magneta');
@ -99,7 +99,7 @@ describe('Lifecycle hooks', () => {
expect(commentEle.isPresent()).toBe(true, 'should have comment because >10 chars'); expect(commentEle.isPresent()).toBe(true, 'should have comment because >10 chars');
expect(commentEle.getText()).toContain('long name'); expect(commentEle.getText()).toContain('long name');
let count = await logEles.count(); const count = await logEles.count();
expect(logCount + 7).toBeGreaterThan(count - 3, '7 additional log messages should have been added'); expect(logCount + 7).toBeGreaterThan(count - 3, '7 additional log messages should have been added');
expect(logCount + 7).toBeLessThan(count + 3, '7 additional log messages should have been added'); expect(logCount + 7).toBeLessThan(count + 3, '7 additional log messages should have been added');
@ -109,18 +109,18 @@ describe('Lifecycle hooks', () => {
}); });
it('should support AfterContent hooks', async () => { it('should support AfterContent hooks', async () => {
let parentEle = element(by.tagName('after-content-parent')); const parentEle = element(by.tagName('after-content-parent'));
let buttonEle = parentEle.element(by.tagName('button')); // Reset const buttonEle = parentEle.element(by.tagName('button')); // Reset
let commentEle = parentEle.element(by.className('comment')); const commentEle = parentEle.element(by.className('comment'));
let logEles = parentEle.all(by.css('h4 ~ div')); const logEles = parentEle.all(by.css('h4 ~ div'));
let childViewInputEle = parentEle.element(by.css('app-child input')); const childViewInputEle = parentEle.element(by.css('app-child input'));
let logCount = await logEles.count(); let logCount = await logEles.count();
expect(childViewInputEle.getAttribute('value')).toContain('Magneta'); expect(childViewInputEle.getAttribute('value')).toContain('Magneta');
expect(commentEle.isPresent()).toBe(false, 'comment should not be in DOM'); expect(commentEle.isPresent()).toBe(false, 'comment should not be in DOM');
await sendKeys(childViewInputEle, '-test-'); await sendKeys(childViewInputEle, '-test-');
let count = await logEles.count(); const count = await logEles.count();
expect(childViewInputEle.getAttribute('value')).toContain('-test-'); expect(childViewInputEle.getAttribute('value')).toContain('-test-');
expect(commentEle.isPresent()).toBe(true, 'should have comment because >10 chars'); expect(commentEle.isPresent()).toBe(true, 'should have comment because >10 chars');
expect(commentEle.getText()).toContain('long name'); expect(commentEle.getText()).toContain('long name');
@ -132,11 +132,11 @@ describe('Lifecycle hooks', () => {
}); });
it('should support spy\'s OnInit & OnDestroy hooks', async () => { it('should support spy\'s OnInit & OnDestroy hooks', async () => {
let inputEle = element(by.css('spy-parent input')); const inputEle = element(by.css('spy-parent input'));
let addHeroButtonEle = element(by.cssContainingText('spy-parent button', 'Add Hero')); const addHeroButtonEle = element(by.cssContainingText('spy-parent button', 'Add Hero'));
let resetHeroesButtonEle = element(by.cssContainingText('spy-parent button', 'Reset Heroes')); const resetHeroesButtonEle = element(by.cssContainingText('spy-parent button', 'Reset Heroes'));
let heroEles = element.all(by.css('spy-parent div[mySpy')); const heroEles = element.all(by.css('spy-parent div[mySpy'));
let logEles = element.all(by.css('spy-parent h4 ~ div')); const logEles = element.all(by.css('spy-parent h4 ~ div'));
expect(heroEles.count()).toBe(2, 'should have two heroes displayed'); expect(heroEles.count()).toBe(2, 'should have two heroes displayed');
expect(logEles.count()).toBe(2, 'should have two log entries'); expect(logEles.count()).toBe(2, 'should have two log entries');
@ -153,10 +153,10 @@ describe('Lifecycle hooks', () => {
}); });
it('should support "spy counter"', async () => { it('should support "spy counter"', async () => {
let updateCounterButtonEle = element(by.cssContainingText('counter-parent button', 'Update')); const updateCounterButtonEle = element(by.cssContainingText('counter-parent button', 'Update'));
let resetCounterButtonEle = element(by.cssContainingText('counter-parent button', 'Reset')); const resetCounterButtonEle = element(by.cssContainingText('counter-parent button', 'Reset'));
let textEle = element(by.css('counter-parent app-counter > div')); const textEle = element(by.css('counter-parent app-counter > div'));
let logEles = element.all(by.css('counter-parent h4 ~ div')); const logEles = element.all(by.css('counter-parent h4 ~ div'));
expect(textEle.getText()).toContain('Counter = 0'); expect(textEle.getText()).toContain('Counter = 0');
expect(logEles.count()).toBe(2, 'should start with two log entries'); expect(logEles.count()).toBe(2, 'should start with two log entries');

View File

@ -67,8 +67,8 @@ export class AfterContentComponent implements AfterContentChecked, AfterContentI
} }
private logIt(method: string) { private logIt(method: string) {
let child = this.contentChild; const child = this.contentChild;
let message = `${method}: ${child ? child.hero : 'no'} child content`; const message = `${method}: ${child ? child.hero : 'no'} child content`;
this.logger.log(message); this.logger.log(message);
} }
// #docregion hooks // #docregion hooks

View File

@ -67,7 +67,7 @@ export class AfterViewComponent implements AfterViewChecked, AfterViewInit {
// #docregion do-something // #docregion do-something
// This surrogate for real business logic sets the `comment` // This surrogate for real business logic sets the `comment`
private doSomething() { private doSomething() {
let c = this.viewChild.hero.length > 10 ? `That's a long name` : ''; const c = this.viewChild.hero.length > 10 ? `That's a long name` : '';
if (c !== this.comment) { if (c !== this.comment) {
// Wait a tick because the component's view has already been checked // Wait a tick because the component's view has already been checked
this.logger.tick_then(() => this.comment = c); this.logger.tick_then(() => this.comment = c);
@ -76,8 +76,8 @@ export class AfterViewComponent implements AfterViewChecked, AfterViewInit {
// #enddocregion do-something // #enddocregion do-something
private logIt(method: string) { private logIt(method: string) {
let child = this.viewChild; const child = this.viewChild;
let message = `${method}: ${child ? child.hero : 'no'} child view`; const message = `${method}: ${child ? child.hero : 'no'} child view`;
this.logger.log(message); this.logger.log(message);
} }
// #docregion hooks // #docregion hooks

View File

@ -31,9 +31,9 @@ export class MyCounterComponent implements OnChanges {
} }
// A change to `counter` is the only change we care about // A change to `counter` is the only change we care about
let chng = changes.counter; const chng = changes.counter;
let cur = chng.currentValue; const cur = chng.currentValue;
let prev = JSON.stringify(chng.previousValue); // first time is {}; after is integer const prev = JSON.stringify(chng.previousValue); // first time is {}; after is integer
this.changeLog.push(`counter: currentValue = ${cur}, previousValue = ${prev}`); this.changeLog.push(`counter: currentValue = ${cur}, previousValue = ${prev}`);
} }
} }

View File

@ -51,8 +51,8 @@ export class DoCheckComponent implements DoCheck {
this.noChangeCount = 0; this.noChangeCount = 0;
} else { } else {
// log that hook was called when there was no relevant change. // log that hook was called when there was no relevant change.
let count = this.noChangeCount += 1; const count = this.noChangeCount += 1;
let noChangeMsg = `DoCheck called ${count}x when no change to hero or power`; const noChangeMsg = `DoCheck called ${count}x when no change to hero or power`;
if (count === 1) { if (count === 1) {
// add new "no change" message // add new "no change" message
this.changeLog.push(noChangeMsg); this.changeLog.push(noChangeMsg);

View File

@ -34,10 +34,10 @@ export class OnChangesComponent implements OnChanges {
// #docregion ng-on-changes // #docregion ng-on-changes
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
for (let propName in changes) { for (const propName in changes) {
let chng = changes[propName]; const chng = changes[propName];
let cur = JSON.stringify(chng.currentValue); const cur = JSON.stringify(chng.currentValue);
let prev = JSON.stringify(chng.previousValue); const prev = JSON.stringify(chng.previousValue);
this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`); this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
} }
} }

View File

@ -48,16 +48,16 @@ export class PeekABooComponent extends PeekABooDirective implements
constructor(logger: LoggerService) { constructor(logger: LoggerService) {
super(logger); super(logger);
let is = this.name ? 'is' : 'is not'; const is = this.name ? 'is' : 'is not';
this.logIt(`name ${is} known at construction`); this.logIt(`name ${is} known at construction`);
} }
// only called for/if there is an @input variable set by parent. // only called for/if there is an @input variable set by parent.
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
let changesMsgs: string[] = []; const changesMsgs: string[] = [];
for (let propName in changes) { for (const propName in changes) {
if (propName === 'name') { if (propName === 'name') {
let name = changes.name.currentValue; const name = changes.name.currentValue;
changesMsgs.push(`name ${this.verb} to "${name}"`); changesMsgs.push(`name ${this.verb} to "${name}"`);
} else { } else {
changesMsgs.push(propName + ' ' + this.verb); changesMsgs.push(propName + ' ' + this.verb);

View File

@ -46,7 +46,7 @@ export class ContactComponent implements OnInit {
} }
onSubmit() { onSubmit() {
let newName = this.contactForm.get('name').value; const newName = this.contactForm.get('name').value;
this.displayMessage('Saved ' + newName); this.displayMessage('Saved ' + newName);
this.contact.name = newName; this.contact.name = newName;
} }

View File

@ -25,7 +25,7 @@ export class CustomersDetailComponent implements OnInit {
private customersService: CustomersService) { } private customersService: CustomersService) { }
ngOnInit() { ngOnInit() {
let id = parseInt(this.route.snapshot.paramMap.get('id'), 10); const id = parseInt(this.route.snapshot.paramMap.get('id'), 10);
this.customersService.getCustomer(id).subscribe(customer => this.customer = customer); this.customersService.getCustomer(id).subscribe(customer => this.customer = customer);
} }
} }

View File

@ -26,13 +26,13 @@ describe('Pipes', () => {
}); });
it('should be able to toggle birthday formats', () => { it('should be able to toggle birthday formats', () => {
let birthDayEle = element(by.css('app-hero-birthday2 > p')); const birthDayEle = element(by.css('app-hero-birthday2 > p'));
if (angularVersion.indexOf('4.') === 0) { // Breaking change between v4 and v5 (https://github.com/angular/angular/commit/079d884) if (angularVersion.indexOf('4.') === 0) { // Breaking change between v4 and v5 (https://github.com/angular/angular/commit/079d884)
expect(birthDayEle.getText()).toEqual(`The hero's birthday is 4/15/1988`); expect(birthDayEle.getText()).toEqual(`The hero's birthday is 4/15/1988`);
} else { } else {
expect(birthDayEle.getText()).toEqual(`The hero's birthday is 4/15/88`); expect(birthDayEle.getText()).toEqual(`The hero's birthday is 4/15/88`);
} }
let buttonEle = element(by.cssContainingText('app-hero-birthday2 > button', 'Toggle Format')); const buttonEle = element(by.cssContainingText('app-hero-birthday2 > button', 'Toggle Format'));
expect(buttonEle.isDisplayed()).toBe(true); expect(buttonEle.isDisplayed()).toBe(true);
buttonEle.click().then(() => { buttonEle.click().then(() => {
expect(birthDayEle.getText()).toEqual(`The hero's birthday is Friday, April 15, 1988`); expect(birthDayEle.getText()).toEqual(`The hero's birthday is Friday, April 15, 1988`);
@ -40,7 +40,7 @@ describe('Pipes', () => {
}); });
it('should be able to chain and compose pipes', () => { it('should be able to chain and compose pipes', () => {
let chainedPipeEles = element.all(by.cssContainingText('app-root p', `The chained hero's`)); const chainedPipeEles = element.all(by.cssContainingText('app-root p', `The chained hero's`));
expect(chainedPipeEles.count()).toBe(3, 'should have 3 chained pipe examples'); expect(chainedPipeEles.count()).toBe(3, 'should have 3 chained pipe examples');
expect(chainedPipeEles.get(0).getText()).toContain('APR 15, 1988'); expect(chainedPipeEles.get(0).getText()).toContain('APR 15, 1988');
expect(chainedPipeEles.get(1).getText()).toContain('FRIDAY, APRIL 15, 1988'); expect(chainedPipeEles.get(1).getText()).toContain('FRIDAY, APRIL 15, 1988');
@ -48,15 +48,15 @@ describe('Pipes', () => {
}); });
it('should be able to use ExponentialStrengthPipe pipe', () => { it('should be able to use ExponentialStrengthPipe pipe', () => {
let ele = element(by.css('app-power-booster p')); const ele = element(by.css('app-power-booster p'));
expect(ele.getText()).toContain('Super power boost: 1024'); expect(ele.getText()).toContain('Super power boost: 1024');
}); });
it('should be able to use the exponential calculator', () => { it('should be able to use the exponential calculator', () => {
let eles = element.all(by.css('app-power-boost-calculator input')); const eles = element.all(by.css('app-power-boost-calculator input'));
let baseInputEle = eles.get(0); const baseInputEle = eles.get(0);
let factorInputEle = eles.get(1); const factorInputEle = eles.get(1);
let outputEle = element(by.css('app-power-boost-calculator p')); const outputEle = element(by.css('app-power-boost-calculator p'));
baseInputEle.clear().then(() => { baseInputEle.clear().then(() => {
baseInputEle.sendKeys('7'); baseInputEle.sendKeys('7');
return factorInputEle.clear(); return factorInputEle.clear();
@ -68,11 +68,11 @@ describe('Pipes', () => {
it('should support flying heroes (pure) ', () => { it('should support flying heroes (pure) ', () => {
let nameEle = element(by.css('app-flying-heroes input[type="text"]')); const nameEle = element(by.css('app-flying-heroes input[type="text"]'));
let canFlyCheckEle = element(by.css('app-flying-heroes #can-fly')); const canFlyCheckEle = element(by.css('app-flying-heroes #can-fly'));
let mutateCheckEle = element(by.css('app-flying-heroes #mutate')); const mutateCheckEle = element(by.css('app-flying-heroes #mutate'));
let resetEle = element(by.css('app-flying-heroes button')); const resetEle = element(by.css('app-flying-heroes button'));
let flyingHeroesEle = element.all(by.css('app-flying-heroes #flyers div')); const flyingHeroesEle = element.all(by.css('app-flying-heroes #flyers div'));
expect(canFlyCheckEle.getAttribute('checked')).toEqual('true', 'should default to "can fly"'); expect(canFlyCheckEle.getAttribute('checked')).toEqual('true', 'should default to "can fly"');
expect(mutateCheckEle.getAttribute('checked')).toEqual('true', 'should default to mutating array'); expect(mutateCheckEle.getAttribute('checked')).toEqual('true', 'should default to mutating array');
@ -94,10 +94,10 @@ describe('Pipes', () => {
it('should support flying heroes (impure) ', () => { it('should support flying heroes (impure) ', () => {
let nameEle = element(by.css('app-flying-heroes-impure input[type="text"]')); const nameEle = element(by.css('app-flying-heroes-impure input[type="text"]'));
let canFlyCheckEle = element(by.css('app-flying-heroes-impure #can-fly')); const canFlyCheckEle = element(by.css('app-flying-heroes-impure #can-fly'));
let mutateCheckEle = element(by.css('app-flying-heroes-impure #mutate')); const mutateCheckEle = element(by.css('app-flying-heroes-impure #mutate'));
let flyingHeroesEle = element.all(by.css('app-flying-heroes-impure #flyers div')); const flyingHeroesEle = element.all(by.css('app-flying-heroes-impure #flyers div'));
expect(canFlyCheckEle.getAttribute('checked')).toEqual('true', 'should default to "can fly"'); expect(canFlyCheckEle.getAttribute('checked')).toEqual('true', 'should default to "can fly"');
expect(mutateCheckEle.getAttribute('checked')).toEqual('true', 'should default to mutating array'); expect(mutateCheckEle.getAttribute('checked')).toEqual('true', 'should default to mutating array');

View File

@ -23,7 +23,7 @@ export class FlyingHeroesComponent {
addHero(name: string) { addHero(name: string) {
name = name.trim(); name = name.trim();
if (!name) { return; } if (!name) { return; }
let hero = {name, canFly: this.canFly}; const hero = {name, canFly: this.canFly};
// #enddocregion v1 // #enddocregion v1
if (this.mutate) { if (this.mutate) {
// Pure pipe won't update display because heroes array reference is unchanged // Pure pipe won't update display because heroes array reference is unchanged

View File

@ -100,7 +100,7 @@ describe('Router', () => {
await page.heroesHref.click(); await page.heroesHref.click();
await browser.sleep(600); await browser.sleep(600);
const heroEle = page.heroesList.get(4); const heroEle = page.heroesList.get(4);
let text = await heroEle.getText(); const text = await heroEle.getText();
expect(text.length).toBeGreaterThan(0, 'hero item text length'); expect(text.length).toBeGreaterThan(0, 'hero item text length');
// remove leading id from text // remove leading id from text
const heroText = text.substr(text.indexOf(' ')).trim(); const heroText = text.substr(text.indexOf(' ')).trim();
@ -110,11 +110,11 @@ describe('Router', () => {
expect(page.heroesList.count()).toBe(0, 'hero list count'); expect(page.heroesList.count()).toBe(0, 'hero list count');
expect(page.heroDetail.isPresent()).toBe(true, 'hero detail'); expect(page.heroDetail.isPresent()).toBe(true, 'hero detail');
expect(page.heroDetailTitle.getText()).toContain(heroText); expect(page.heroDetailTitle.getText()).toContain(heroText);
let inputEle = page.heroDetail.element(by.css('input')); const inputEle = page.heroDetail.element(by.css('input'));
await inputEle.sendKeys('-foo'); await inputEle.sendKeys('-foo');
expect(page.heroDetailTitle.getText()).toContain(heroText + '-foo'); expect(page.heroDetailTitle.getText()).toContain(heroText + '-foo');
let buttonEle = page.heroDetail.element(by.css('button')); const buttonEle = page.heroDetail.element(by.css('button'));
await buttonEle.click(); await buttonEle.click();
await browser.sleep(600); await browser.sleep(600);
expect(heroEle.getText()).toContain(heroText + '-foo'); expect(heroEle.getText()).toContain(heroText + '-foo');
@ -166,7 +166,7 @@ describe('Router', () => {
const page = getPageStruct(); const page = getPageStruct();
await page.crisisHref.click(); await page.crisisHref.click();
let crisisEle = page.crisisList.get(index); let crisisEle = page.crisisList.get(index);
let text = await crisisEle.getText(); const text = await crisisEle.getText();
expect(text.length).toBeGreaterThan(0, 'crisis item text length'); expect(text.length).toBeGreaterThan(0, 'crisis item text length');
// remove leading id from text // remove leading id from text
const crisisText = text.substr(text.indexOf(' ')).trim(); const crisisText = text.substr(text.indexOf(' ')).trim();
@ -174,10 +174,10 @@ describe('Router', () => {
await crisisEle.click(); await crisisEle.click();
expect(page.crisisDetail.isPresent()).toBe(true, 'crisis detail present'); expect(page.crisisDetail.isPresent()).toBe(true, 'crisis detail present');
expect(page.crisisDetailTitle.getText()).toContain(crisisText); expect(page.crisisDetailTitle.getText()).toContain(crisisText);
let inputEle = page.crisisDetail.element(by.css('input')); const inputEle = page.crisisDetail.element(by.css('input'));
await inputEle.sendKeys('-foo'); await inputEle.sendKeys('-foo');
let buttonEle = page.crisisDetail.element(by.buttonText(save ? 'Save' : 'Cancel')); const buttonEle = page.crisisDetail.element(by.buttonText(save ? 'Save' : 'Cancel'));
await buttonEle.click(); await buttonEle.click();
crisisEle = page.crisisList.get(index); crisisEle = page.crisisList.get(index);
if (save) { if (save) {

View File

@ -13,7 +13,7 @@ export class AuthGuard implements CanActivate {
canActivate( canActivate(
next: ActivatedRouteSnapshot, next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): true|UrlTree { state: RouterStateSnapshot): true|UrlTree {
let url: string = state.url; const url: string = state.url;
return this.checkLogin(url); return this.checkLogin(url);
} }

View File

@ -18,7 +18,7 @@ export class AuthGuard implements CanActivate, CanActivateChild {
canActivate( canActivate(
route: ActivatedRouteSnapshot, route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): true|UrlTree { state: RouterStateSnapshot): true|UrlTree {
let url: string = state.url; const url: string = state.url;
return this.checkLogin(url); return this.checkLogin(url);
} }

View File

@ -18,7 +18,7 @@ export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private authService: AuthService, private router: Router) {} constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): true|UrlTree { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): true|UrlTree {
let url: string = state.url; const url: string = state.url;
return this.checkLogin(url); return this.checkLogin(url);
} }
@ -34,11 +34,11 @@ export class AuthGuard implements CanActivate, CanActivateChild {
this.authService.redirectUrl = url; this.authService.redirectUrl = url;
// Create a dummy session id // Create a dummy session id
let sessionId = 123456789; const sessionId = 123456789;
// Set our navigation extras object // Set our navigation extras object
// that contains our global query params and fragment // that contains our global query params and fragment
let navigationExtras: NavigationExtras = { const navigationExtras: NavigationExtras = {
queryParams: { session_id: sessionId }, queryParams: { session_id: sessionId },
fragment: 'anchor' fragment: 'anchor'
}; };

View File

@ -17,7 +17,7 @@ export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
constructor(private authService: AuthService, private router: Router) {} constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url; const url: string = state.url;
return this.checkLogin(url); return this.checkLogin(url);
} }
@ -28,7 +28,7 @@ export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
// #docregion, canLoad // #docregion, canLoad
canLoad(route: Route): boolean { canLoad(route: Route): boolean {
let url = `/${route.path}`; const url = `/${route.path}`;
return this.checkLogin(url); return this.checkLogin(url);
} }
@ -41,11 +41,11 @@ export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
this.authService.redirectUrl = url; this.authService.redirectUrl = url;
// Create a dummy session id // Create a dummy session id
let sessionId = 123456789; const sessionId = 123456789;
// Set our navigation extras object // Set our navigation extras object
// that contains our global query params and fragment // that contains our global query params and fragment
let navigationExtras: NavigationExtras = { const navigationExtras: NavigationExtras = {
queryParams: { session_id: sessionId }, queryParams: { session_id: sessionId },
fragment: 'anchor' fragment: 'anchor'
}; };

View File

@ -32,7 +32,7 @@ export class LoginComponent {
// #docregion preserve // #docregion preserve
// Set our navigation extras object // Set our navigation extras object
// that passes on our global query params and fragment // that passes on our global query params and fragment
let navigationExtras: NavigationExtras = { const navigationExtras: NavigationExtras = {
queryParamsHandling: 'preserve', queryParamsHandling: 'preserve',
preserveFragment: true preserveFragment: true
}; };

View File

@ -19,7 +19,7 @@ export class CrisisDetailResolverService implements Resolve<Crisis> {
constructor(private cs: CrisisService, private router: Router) {} constructor(private cs: CrisisService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Crisis> | Observable<never> { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Crisis> | Observable<never> {
let id = route.paramMap.get('id'); const id = route.paramMap.get('id');
return this.cs.getCrisis(id).pipe( return this.cs.getCrisis(id).pipe(
take(1), take(1),

View File

@ -62,7 +62,7 @@ export class CrisisDetailComponent implements OnInit {
} }
gotoCrises() { gotoCrises() {
let crisisId = this.crisis ? this.crisis.id : null; const crisisId = this.crisis ? this.crisis.id : null;
// Pass along the crisis id if available // Pass along the crisis id if available
// so that the CrisisListComponent can select that crisis. // so that the CrisisListComponent can select that crisis.
// Add a totally useless `foo` parameter for kicks. // Add a totally useless `foo` parameter for kicks.

View File

@ -56,7 +56,7 @@ export class CrisisDetailComponent implements OnInit {
// #enddocregion canDeactivate // #enddocregion canDeactivate
gotoCrises() { gotoCrises() {
let crisisId = this.crisis ? this.crisis.id : null; const crisisId = this.crisis ? this.crisis.id : null;
// Pass along the crisis id if available // Pass along the crisis id if available
// so that the CrisisListComponent can select that crisis. // so that the CrisisListComponent can select that crisis.
// Add a totally useless `foo` parameter for kicks. // Add a totally useless `foo` parameter for kicks.

View File

@ -29,7 +29,7 @@ export class CrisisService {
addCrisis(name: string) { addCrisis(name: string) {
name = name.trim(); name = name.trim();
if (name) { if (name) {
let crisis = { id: CrisisService.nextCrisisId++, name }; const crisis = { id: CrisisService.nextCrisisId++, name };
CRISES.push(crisis); CRISES.push(crisis);
this.crises$.next(CRISES); this.crises$.next(CRISES);
} }

View File

@ -23,7 +23,7 @@ export class HeroDetailComponent implements OnInit {
// #docregion snapshot // #docregion snapshot
ngOnInit() { ngOnInit() {
let id = this.route.snapshot.paramMap.get('id'); const id = this.route.snapshot.paramMap.get('id');
this.hero$ = this.service.getHero(id); this.hero$ = this.service.getHero(id);
} }

View File

@ -37,7 +37,7 @@ export class HeroDetailComponent implements OnInit {
// #docregion gotoHeroes // #docregion gotoHeroes
gotoHeroes(hero: Hero) { gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null; const heroId = hero ? hero.id : null;
// Pass along the hero id if available // Pass along the hero id if available
// so that the HeroList component can select that hero. // so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun. // Include a junk 'foo' property for fun.

View File

@ -38,7 +38,7 @@ export class HeroDetailComponent implements OnInit {
// #docregion redirect // #docregion redirect
gotoHeroes(hero: Hero) { gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null; const heroId = hero ? hero.id : null;
// Pass along the hero id if available // Pass along the hero id if available
// so that the HeroList component can select that hero. // so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun. // Include a junk 'foo' property for fun.

View File

@ -4,32 +4,32 @@ describe('Security E2E Tests', () => {
beforeAll(() => browser.get('')); beforeAll(() => browser.get(''));
it('sanitizes innerHTML', () => { it('sanitizes innerHTML', () => {
let interpolated = element(By.className('e2e-inner-html-interpolated')); const interpolated = element(By.className('e2e-inner-html-interpolated'));
expect(interpolated.getText()) expect(interpolated.getText())
.toContain('Template <script>alert("0wned")</script> <b>Syntax</b>'); .toContain('Template <script>alert("0wned")</script> <b>Syntax</b>');
let bound = element(By.className('e2e-inner-html-bound')); const bound = element(By.className('e2e-inner-html-bound'));
expect(bound.getText()).toContain('Template Syntax'); expect(bound.getText()).toContain('Template Syntax');
let bold = element(By.css('.e2e-inner-html-bound b')); const bold = element(By.css('.e2e-inner-html-bound b'));
expect(bold.getText()).toContain('Syntax'); expect(bold.getText()).toContain('Syntax');
}); });
it('escapes untrusted URLs', () => { it('escapes untrusted URLs', () => {
let untrustedUrl = element(By.className('e2e-dangerous-url')); const untrustedUrl = element(By.className('e2e-dangerous-url'));
expect(untrustedUrl.getAttribute('href')).toMatch(/^unsafe:javascript/); expect(untrustedUrl.getAttribute('href')).toMatch(/^unsafe:javascript/);
}); });
it('binds trusted URLs', () => { it('binds trusted URLs', () => {
let trustedUrl = element(By.className('e2e-trusted-url')); const trustedUrl = element(By.className('e2e-trusted-url'));
expect(trustedUrl.getAttribute('href')).toMatch(/^javascript:alert/); expect(trustedUrl.getAttribute('href')).toMatch(/^javascript:alert/);
}); });
it('escapes untrusted resource URLs', () => { it('escapes untrusted resource URLs', () => {
let iframe = element(By.className('e2e-iframe-untrusted-src')); const iframe = element(By.className('e2e-iframe-untrusted-src'));
expect(iframe.getAttribute('src')).toBe(''); expect(iframe.getAttribute('src')).toBe('');
}); });
it('binds trusted resource URLs', () => { it('binds trusted resource URLs', () => {
let iframe = element(By.className('e2e-iframe-trusted-src')); const iframe = element(By.className('e2e-iframe-trusted-src'));
expect(iframe.getAttribute('src')).toMatch(/^https:\/\/www.youtube.com\//); expect(iframe.getAttribute('src')).toMatch(/^https:\/\/www.youtube.com\//);
}); });
}); });

View File

@ -15,7 +15,7 @@ describe('sw-example App', () => {
}); });
it('should display the Angular logo', () => { it('should display the Angular logo', () => {
let logo = element(by.css('img')); const logo = element(by.css('img'));
page.navigateTo(); page.navigateTo();
expect(logo.isPresent()).toBe(true); expect(logo.isPresent()).toBe(true);
}); });

View File

@ -6,7 +6,7 @@ describe('Set Document Title', () => {
it('should set the document title', () => { it('should set the document title', () => {
let titles = [ const titles = [
'Good morning!', 'Good morning!',
'Good afternoon!', 'Good afternoon!',
'Good evening!' 'Good evening!'

View File

@ -2,7 +2,7 @@ import { browser, element, by } from 'protractor';
describe('QuickStart E2E Tests', () => { describe('QuickStart E2E Tests', () => {
let expectedMsg = 'Hello Angular'; const expectedMsg = 'Hello Angular';
beforeEach(() => { beforeEach(() => {
browser.get(''); browser.get('');

View File

@ -4,7 +4,7 @@ describe('Style Guide', () => {
it('01-01', () => { it('01-01', () => {
browser.get('#/01-01'); browser.get('#/01-01');
let pre = element(by.tagName('toh-heroes > pre')); const pre = element(by.tagName('toh-heroes > pre'));
expect(pre.getText()).toContain('Bombasto'); expect(pre.getText()).toContain('Bombasto');
expect(pre.getText()).toContain('Tornado'); expect(pre.getText()).toContain('Tornado');
expect(pre.getText()).toContain('Magneta'); expect(pre.getText()).toContain('Magneta');
@ -13,8 +13,8 @@ describe('Style Guide', () => {
it('02-07', () => { it('02-07', () => {
browser.get('#/02-07'); browser.get('#/02-07');
let hero = element(by.tagName('toh-hero > div')); const hero = element(by.tagName('toh-hero > div'));
let users = element(by.tagName('admin-users > div')); const users = element(by.tagName('admin-users > div'));
expect(hero.getText()).toBe('hero component'); expect(hero.getText()).toBe('hero component');
expect(users.getText()).toBe('users component'); expect(users.getText()).toBe('users component');
@ -23,77 +23,77 @@ describe('Style Guide', () => {
it('02-08', () => { it('02-08', () => {
browser.get('#/02-08'); browser.get('#/02-08');
let input = element(by.tagName('input[tohvalidate]')); const input = element(by.tagName('input[tohvalidate]'));
expect(input.isPresent()).toBe(true); expect(input.isPresent()).toBe(true);
}); });
it('04-10', () => { it('04-10', () => {
browser.get('#/04-10'); browser.get('#/04-10');
let div = element(by.tagName('sg-app > toh-heroes > div')); const div = element(by.tagName('sg-app > toh-heroes > div'));
expect(div.getText()).toBe('This is heroes component'); expect(div.getText()).toBe('This is heroes component');
}); });
it('05-02', () => { it('05-02', () => {
browser.get('#/05-02'); browser.get('#/05-02');
let button = element(by.tagName('sg-app > toh-hero-button > button')); const button = element(by.tagName('sg-app > toh-hero-button > button'));
expect(button.getText()).toBe('Hero button'); expect(button.getText()).toBe('Hero button');
}); });
it('05-03', () => { it('05-03', () => {
browser.get('#/05-03'); browser.get('#/05-03');
let button = element(by.tagName('sg-app > toh-hero-button > button')); const button = element(by.tagName('sg-app > toh-hero-button > button'));
expect(button.getText()).toBe('Hero button'); expect(button.getText()).toBe('Hero button');
}); });
it('05-04', () => { it('05-04', () => {
browser.get('#/05-04'); browser.get('#/05-04');
let h2 = element(by.tagName('sg-app > toh-heroes > div > h2')); const h2 = element(by.tagName('sg-app > toh-heroes > div > h2'));
expect(h2.getText()).toBe('My Heroes'); expect(h2.getText()).toBe('My Heroes');
}); });
it('05-12', () => { it('05-12', () => {
browser.get('#/05-12'); browser.get('#/05-12');
let button = element(by.tagName('sg-app > toh-hero-button > button')); const button = element(by.tagName('sg-app > toh-hero-button > button'));
expect(button.getText()).toBe('OK'); expect(button.getText()).toBe('OK');
}); });
it('05-13', () => { it('05-13', () => {
browser.get('#/05-13'); browser.get('#/05-13');
let button = element(by.tagName('sg-app > toh-hero-button > button')); const button = element(by.tagName('sg-app > toh-hero-button > button'));
expect(button.getText()).toBe('OK'); expect(button.getText()).toBe('OK');
}); });
it('05-14', () => { it('05-14', () => {
browser.get('#/05-14'); browser.get('#/05-14');
let toast = element(by.tagName('sg-app > toh-toast')); const toast = element(by.tagName('sg-app > toh-toast'));
expect(toast.getText()).toBe('...'); expect(toast.getText()).toBe('...');
}); });
it('05-15', () => { it('05-15', () => {
browser.get('#/05-15'); browser.get('#/05-15');
let heroList = element(by.tagName('sg-app > toh-hero-list')); const heroList = element(by.tagName('sg-app > toh-hero-list'));
expect(heroList.getText()).toBe('...'); expect(heroList.getText()).toBe('...');
}); });
it('05-16', () => { it('05-16', () => {
browser.get('#/05-16'); browser.get('#/05-16');
let hero = element(by.tagName('sg-app > toh-hero')); const hero = element(by.tagName('sg-app > toh-hero'));
expect(hero.getText()).toBe('...'); expect(hero.getText()).toBe('...');
}); });
it('05-17', () => { it('05-17', () => {
browser.get('#/05-17'); browser.get('#/05-17');
let section = element(by.tagName('sg-app > toh-hero-list > section')); const section = element(by.tagName('sg-app > toh-hero-list > section'));
expect(section.getText()).toContain('Our list of heroes'); expect(section.getText()).toContain('Our list of heroes');
expect(section.getText()).toContain('Total powers'); expect(section.getText()).toContain('Total powers');
expect(section.getText()).toContain('Average power'); expect(section.getText()).toContain('Average power');
@ -102,14 +102,14 @@ describe('Style Guide', () => {
it('06-01', () => { it('06-01', () => {
browser.get('#/06-01'); browser.get('#/06-01');
let div = element(by.tagName('sg-app > div[tohhighlight]')); const div = element(by.tagName('sg-app > div[tohhighlight]'));
expect(div.getText()).toBe('Bombasta'); expect(div.getText()).toBe('Bombasta');
}); });
it('06-03', () => { it('06-03', () => {
browser.get('#/06-03'); browser.get('#/06-03');
let input = element(by.tagName('input[tohvalidator]')); const input = element(by.tagName('input[tohvalidator]'));
expect(input.isPresent()).toBe(true); expect(input.isPresent()).toBe(true);
}); });
@ -117,7 +117,7 @@ describe('Style Guide', () => {
xit('07-01', () => { xit('07-01', () => {
browser.get('#/07-01'); browser.get('#/07-01');
let lis = element.all(by.tagName('sg-app > ul > li')); const lis = element.all(by.tagName('sg-app > ul > li'));
expect(lis.get(0).getText()).toBe('Windstorm'); expect(lis.get(0).getText()).toBe('Windstorm');
expect(lis.get(1).getText()).toBe('Bombasto'); expect(lis.get(1).getText()).toBe('Bombasto');
expect(lis.get(2).getText()).toBe('Magneta'); expect(lis.get(2).getText()).toBe('Magneta');
@ -127,21 +127,21 @@ describe('Style Guide', () => {
it('07-03', () => { it('07-03', () => {
browser.get('#/07-03'); browser.get('#/07-03');
let pre = element(by.tagName('toh-heroes > pre')); const pre = element(by.tagName('toh-heroes > pre'));
expect(pre.getText()).toContain('[]'); expect(pre.getText()).toContain('[]');
}); });
it('07-04', () => { it('07-04', () => {
browser.get('#/07-04'); browser.get('#/07-04');
let pre = element(by.tagName('toh-app > pre')); const pre = element(by.tagName('toh-app > pre'));
expect(pre.getText()).toContain('[]'); expect(pre.getText()).toContain('[]');
}); });
it('09-01', () => { it('09-01', () => {
browser.get('#/09-01'); browser.get('#/09-01');
let button = element(by.tagName('sg-app > toh-hero-button > button')); const button = element(by.tagName('sg-app > toh-hero-button > button'));
expect(button.getText()).toBe('OK'); expect(button.getText()).toBe('OK');
}); });
}); });

View File

@ -11,9 +11,9 @@ export class FilterTextService {
let filteredList: any[]; let filteredList: any[];
if (data && props && originalList) { if (data && props && originalList) {
data = data.toLowerCase(); data = data.toLowerCase();
let filtered = originalList.filter(item => { const filtered = originalList.filter(item => {
let match = false; let match = false;
for (let prop of props) { for (const prop of props) {
if (item[prop].toString().toLowerCase().indexOf(data) > -1) { if (item[prop].toString().toLowerCase().indexOf(data) > -1) {
match = true; match = true;
break; break;

View File

@ -8,7 +8,7 @@ import { Hero } from './hero.model';
@Injectable() @Injectable()
export class HeroService { export class HeroService {
getHeroes() { getHeroes() {
let heroes: Hero[] = []; const heroes: Hero[] = [];
return of(heroes); return of(heroes);
} }
} }

View File

@ -10,7 +10,7 @@ import { Hero } from './hero.model';
}) })
export class HeroService { export class HeroService {
getHeroes() { getHeroes() {
let heroes: Hero[] = []; const heroes: Hero[] = [];
return of(heroes); return of(heroes);
} }
} }

View File

@ -8,7 +8,7 @@ import { Hero } from './hero.model';
@Injectable() @Injectable()
export class HeroService { export class HeroService {
getHeroes() { getHeroes() {
let heroes: Hero[] = []; const heroes: Hero[] = [];
return of(heroes); return of(heroes);
} }
} }

View File

@ -1,6 +1,6 @@
export class HeroData { export class HeroData {
createDb() { createDb() {
let heroes = [ const heroes = [
{ id: 1, name: 'Windstorm' }, { id: 1, name: 'Windstorm' },
{ id: 2, name: 'Bombasto' }, { id: 2, name: 'Bombasto' },
{ id: 3, name: 'Magneta' }, { id: 3, name: 'Magneta' },

View File

@ -8,22 +8,22 @@ describe('Template Expression Operators', () => {
}); });
it('should have title Inputs and Outputs', () => { it('should have title Inputs and Outputs', () => {
let title = element.all(by.css('h1')).get(0); const title = element.all(by.css('h1')).get(0);
expect(title.getText()).toEqual('Template Expression Operators'); expect(title.getText()).toEqual('Template Expression Operators');
}); });
it('should display json data', () => { it('should display json data', () => {
let jsonDate = element.all(by.css('p')).get(4); const jsonDate = element.all(by.css('p')).get(4);
expect(jsonDate.getText()).toContain('1980'); expect(jsonDate.getText()).toContain('1980');
}); });
it('should display $98', () => { it('should display $98', () => {
let jsonDate = element.all(by.css('p')).get(5); const jsonDate = element.all(by.css('p')).get(5);
expect(jsonDate.getText()).toContain('$98.00'); expect(jsonDate.getText()).toContain('$98.00');
}); });
it('should display Telephone', () => { it('should display Telephone', () => {
let jsonDate = element.all(by.css('p')).get(6); const jsonDate = element.all(by.css('p')).get(6);
expect(jsonDate.getText()).toContain('Telephone'); expect(jsonDate.getText()).toContain('Telephone');
}); });

View File

@ -21,8 +21,8 @@ describe('Template-reference-variables-example', () => {
}); });
it('should log a Calling 123 ... message', async () => { it('should log a Calling 123 ... message', async () => {
let callButton = element.all(by.css('button')).get(0); const callButton = element.all(by.css('button')).get(0);
let phoneInput = element.all(by.css('input')).get(0); const phoneInput = element.all(by.css('input')).get(0);
await phoneInput.sendKeys('123'); await phoneInput.sendKeys('123');
await callButton.click(); await callButton.click();
const contents = 'Calling 123 ...'; const contents = 'Calling 123 ...';
@ -30,8 +30,8 @@ describe('Template-reference-variables-example', () => {
}); });
it('should log a Faxing 123 ... message', async () => { it('should log a Faxing 123 ... message', async () => {
let faxButton = element.all(by.css('button')).get(1); const faxButton = element.all(by.css('button')).get(1);
let faxInput = element.all(by.css('input')).get(1); const faxInput = element.all(by.css('input')).get(1);
await faxInput.sendKeys('123'); await faxInput.sendKeys('123');
await faxButton.click(); await faxButton.click();
const contents = 'Faxing 123 ...'; const contents = 'Faxing 123 ...';
@ -39,13 +39,13 @@ describe('Template-reference-variables-example', () => {
}); });
it('should display a disabled button', () => { it('should display a disabled button', () => {
let disabledButton = element.all(by.css('button')).get(2); const disabledButton = element.all(by.css('button')).get(2);
expect(disabledButton.isEnabled()).toBe(false); expect(disabledButton.isEnabled()).toBe(false);
}); });
it('should submit form', async () => { it('should submit form', async () => {
let submitButton = element.all(by.css('button')).get(3); const submitButton = element.all(by.css('button')).get(3);
let nameInput = element.all(by.css('input')).get(2); const nameInput = element.all(by.css('input')).get(2);
await nameInput.sendKeys('123'); await nameInput.sendKeys('123');
await submitButton.click(); await submitButton.click();
expect(element.all(by.css('div > p')).get(2).getText()).toEqual('Submitted. Form value is {"name":"123"}'); expect(element.all(by.css('div > p')).get(2).getText()).toEqual('Submitted. Form value is {"name":"123"}');

View File

@ -6,7 +6,7 @@ describe('Testing Example', () => {
beforeAll(() => browser.get('')); beforeAll(() => browser.get(''));
function getPageElts() { function getPageElts() {
let navElts = element.all(by.css('app-root nav a')); const navElts = element.all(by.css('app-root nav a'));
return { return {
navElts, navElts,
@ -20,13 +20,13 @@ describe('Testing Example', () => {
}); });
it(`has views ${expectedViewNames}`, async () => { it(`has views ${expectedViewNames}`, async () => {
let viewNames = getPageElts().navElts.map(async (el: ElementFinder) => await el.getText()); const viewNames = getPageElts().navElts.map(async (el: ElementFinder) => await el.getText());
expect(viewNames).toEqual(expectedViewNames); expect(viewNames).toEqual(expectedViewNames);
}); });
it('has dashboard as the active view', () => { it('has dashboard as the active view', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.appDashboard.isPresent()).toBeTruthy(); expect(page.appDashboard.isPresent()).toBeTruthy();
}); });

View File

@ -28,13 +28,13 @@ export class DashboardComponent implements OnInit {
// #docregion goto-detail // #docregion goto-detail
gotoDetail(hero: Hero) { gotoDetail(hero: Hero) {
let url = `/heroes/${hero.id}`; const url = `/heroes/${hero.id}`;
this.router.navigateByUrl(url); this.router.navigateByUrl(url);
} }
// #enddocregion goto-detail // #enddocregion goto-detail
get title() { get title() {
let cnt = this.heroes.length; const cnt = this.heroes.length;
return cnt === 0 ? 'No Heroes' : return cnt === 0 ? 'No Heroes' :
cnt === 1 ? 'Top Hero' : `Top ${cnt} Heroes`; cnt === 1 ? 'Top Hero' : `Top ${cnt} Heroes`;
} }

View File

@ -310,11 +310,11 @@ export class MyIfChildComponent implements OnInit, OnChanges, OnDestroy {
} }
ngOnChanges(changes: {[propertyName: string]: SimpleChange}) { ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
for (let propName in changes) { for (const propName in changes) {
this.ngOnChangesCounter += 1; this.ngOnChangesCounter += 1;
let prop = changes[propName]; const prop = changes[propName];
let cur = JSON.stringify(prop.currentValue); const cur = JSON.stringify(prop.currentValue);
let prev = JSON.stringify(prop.previousValue); const prev = JSON.stringify(prop.previousValue);
this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`); this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
} }
} }

View File

@ -89,7 +89,7 @@ describe('HttpClient testing', () => {
}); });
it('can test multiple requests', () => { it('can test multiple requests', () => {
let testData: Data[] = [ const testData: Data[] = [
{ name: 'bob' }, { name: 'carol' }, { name: 'bob' }, { name: 'carol' },
{ name: 'ted' }, { name: 'alice' } { name: 'ted' }, { name: 'alice' }
]; ];

View File

@ -5,7 +5,7 @@ import { TitleCasePipe } from './title-case.pipe';
// #docregion excerpt, mini-excerpt // #docregion excerpt, mini-excerpt
describe('TitleCasePipe', () => { describe('TitleCasePipe', () => {
// This pipe is a pure, stateless function so no need for BeforeEach // This pipe is a pure, stateless function so no need for BeforeEach
let pipe = new TitleCasePipe(); const pipe = new TitleCasePipe();
it('transforms "abc" to "Abc"', () => { it('transforms "abc" to "Abc"', () => {
expect(pipe.transform('abc')).toBe('Abc'); expect(pipe.transform('abc')).toBe('Abc');

View File

@ -21,7 +21,7 @@ export function advance(f: ComponentFixture<any>): void {
* Although officially deprecated, some browsers (phantom) don't accept the preferred "new Event(eventName)" * Although officially deprecated, some browsers (phantom) don't accept the preferred "new Event(eventName)"
*/ */
export function newEvent(eventName: string, bubbles = false, cancelable = false) { export function newEvent(eventName: string, bubbles = false, cancelable = false) {
let evt = document.createEvent('CustomEvent'); // MUST be 'CustomEvent' const evt = document.createEvent('CustomEvent'); // MUST be 'CustomEvent'
evt.initCustomEvent(eventName, bubbles, cancelable, null); evt.initCustomEvent(eventName, bubbles, cancelable, null);
return evt; return evt;
} }

View File

@ -4,7 +4,7 @@ describe('Tour of Heroes', () => {
beforeEach(() => browser.get('/')); beforeEach(() => browser.get('/'));
it('should display "Tour of Heroes"', () => { it('should display "Tour of Heroes"', () => {
let title = element(by.css('app-root h1')).getText(); const title = element(by.css('app-root h1')).getText();
expect(title).toEqual('Tour of Heroes'); expect(title).toEqual('Tour of Heroes');
}); });
}); });

View File

@ -12,9 +12,9 @@ class Hero {
// Get hero id and name from the given detail element. // Get hero id and name from the given detail element.
static async fromDetail(detail: ElementFinder): Promise<Hero> { static async fromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div> // Get hero id from the first <div>
let id = await detail.all(by.css('div')).first().getText(); const id = await detail.all(by.css('div')).first().getText();
// Get name from the h2 // Get name from the h2
let name = await detail.element(by.css('h2')).getText(); const name = await detail.element(by.css('h2')).getText();
return { return {
id: +id.substr(id.indexOf(' ') + 1), id: +id.substr(id.indexOf(' ') + 1),
name: name.substr(0, name.lastIndexOf(' ')) name: name.substr(0, name.lastIndexOf(' '))
@ -24,7 +24,7 @@ class Hero {
const nameSuffix = 'X'; const nameSuffix = 'X';
function addToHeroName(text: string): promise.Promise<void> { function addToHeroName(text: string): promise.Promise<void> {
let input = element(by.css('input')); const input = element(by.css('input'));
return input.sendKeys(text); return input.sendKeys(text);
} }
@ -39,22 +39,22 @@ describe('Tutorial part 1', () => {
}); });
it(`has h1 '${expectedH1}'`, () => { it(`has h1 '${expectedH1}'`, () => {
let hText = element(by.css('h1')).getText(); const hText = element(by.css('h1')).getText();
expect(hText).toEqual(expectedH1, 'h1'); expect(hText).toEqual(expectedH1, 'h1');
}); });
it(`shows initial hero details`, async () => { it(`shows initial hero details`, async () => {
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(expectedHero.id); expect(hero.id).toEqual(expectedHero.id);
expect(hero.name).toEqual(expectedHero.name.toUpperCase()); expect(hero.name).toEqual(expectedHero.name.toUpperCase());
}); });
it(`shows updated hero name`, async () => { it(`shows updated hero name`, async () => {
addToHeroName(nameSuffix); addToHeroName(nameSuffix);
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
let newName = expectedHero.name + nameSuffix; const newName = expectedHero.name + nameSuffix;
expect(hero.id).toEqual(expectedHero.id); expect(hero.id).toEqual(expectedHero.id);
expect(hero.name).toEqual(newName.toUpperCase()); expect(hero.name).toEqual(newName.toUpperCase());
}); });

View File

@ -24,9 +24,9 @@ class Hero {
// Get hero id and name from the given detail element. // Get hero id and name from the given detail element.
static async fromDetail(detail: ElementFinder): Promise<Hero> { static async fromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div> // Get hero id from the first <div>
let id = await detail.all(by.css('div')).first().getText(); const id = await detail.all(by.css('div')).first().getText();
// Get name from the h2 // Get name from the h2
let name = await detail.element(by.css('h2')).getText(); const name = await detail.element(by.css('h2')).getText();
return { return {
id: +id.substr(id.indexOf(' ') + 1), id: +id.substr(id.indexOf(' ') + 1),
name: name.substr(0, name.lastIndexOf(' ')) name: name.substr(0, name.lastIndexOf(' '))
@ -55,12 +55,12 @@ function initialPageTests() {
}); });
it('has the right number of heroes', () => { it('has the right number of heroes', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.heroes.count()).toEqual(10); expect(page.heroes.count()).toEqual(10);
}); });
it('has no selected hero and no hero details', () => { it('has no selected hero and no hero details', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.selected.isPresent()).toBeFalsy('selected hero'); expect(page.selected.isPresent()).toBeFalsy('selected hero');
expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail'); expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail');
}); });
@ -68,20 +68,20 @@ function initialPageTests() {
function selectHeroTests() { function selectHeroTests() {
it(`selects ${targetHero.name} from hero list`, () => { it(`selects ${targetHero.name} from hero list`, () => {
let hero = element(by.cssContainingText('li span.badge', targetHero.id.toString())); const hero = element(by.cssContainingText('li span.badge', targetHero.id.toString()));
hero.click(); hero.click();
// Nothing specific to expect other than lack of exceptions. // Nothing specific to expect other than lack of exceptions.
}); });
it(`has selected ${targetHero.name}`, () => { it(`has selected ${targetHero.name}`, () => {
let page = getPageElts(); const page = getPageElts();
let expectedText = `${targetHero.id} ${targetHero.name}`; const expectedText = `${targetHero.id} ${targetHero.name}`;
expect(page.selected.getText()).toBe(expectedText); expect(page.selected.getText()).toBe(expectedText);
}); });
it('shows selected hero details', async () => { it('shows selected hero details', async () => {
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase()); expect(hero.name).toEqual(targetHero.name.toUpperCase());
}); });
@ -94,17 +94,17 @@ function updateHeroTests() {
}); });
it(`shows updated hero name in details`, async () => { it(`shows updated hero name in details`, async () => {
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
let newName = targetHero.name + nameSuffix; const newName = targetHero.name + nameSuffix;
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newName.toUpperCase()); expect(hero.name).toEqual(newName.toUpperCase());
}); });
it(`shows updated hero name in list`, async () => { it(`shows updated hero name in list`, async () => {
let page = getPageElts(); const page = getPageElts();
let hero = Hero.fromString(await page.selected.getText()); const hero = Hero.fromString(await page.selected.getText());
let newName = targetHero.name + nameSuffix; const newName = targetHero.name + nameSuffix;
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newName); expect(hero.name).toEqual(newName);
}); });
@ -112,13 +112,13 @@ function updateHeroTests() {
} }
function addToHeroName(text: string): promise.Promise<void> { function addToHeroName(text: string): promise.Promise<void> {
let input = element(by.css('input')); const input = element(by.css('input'));
return input.sendKeys(text); return input.sendKeys(text);
} }
function expectHeading(hLevel: number, expectedText: string): void { function expectHeading(hLevel: number, expectedText: string): void {
let hTag = `h${hLevel}`; const hTag = `h${hLevel}`;
let hText = element(by.css(hTag)).getText(); const hText = element(by.css(hTag)).getText();
expect(hText).toEqual(expectedText, hTag); expect(hText).toEqual(expectedText, hTag);
} }

View File

@ -24,9 +24,9 @@ class Hero {
// Get hero id and name from the given detail element. // Get hero id and name from the given detail element.
static async fromDetail(detail: ElementFinder): Promise<Hero> { static async fromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div> // Get hero id from the first <div>
let id = await detail.all(by.css('div')).first().getText(); const id = await detail.all(by.css('div')).first().getText();
// Get name from the h2 // Get name from the h2
let name = await detail.element(by.css('h2')).getText(); const name = await detail.element(by.css('h2')).getText();
return { return {
id: +id.substr(id.indexOf(' ') + 1), id: +id.substr(id.indexOf(' ') + 1),
name: name.substr(0, name.lastIndexOf(' ')) name: name.substr(0, name.lastIndexOf(' '))
@ -55,12 +55,12 @@ function initialPageTests() {
}); });
it('has the right number of heroes', () => { it('has the right number of heroes', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.heroes.count()).toEqual(10); expect(page.heroes.count()).toEqual(10);
}); });
it('has no selected hero and no hero details', () => { it('has no selected hero and no hero details', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.selected.isPresent()).toBeFalsy('selected hero'); expect(page.selected.isPresent()).toBeFalsy('selected hero');
expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail'); expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail');
}); });
@ -68,20 +68,20 @@ function initialPageTests() {
function selectHeroTests() { function selectHeroTests() {
it(`selects ${targetHero.name} from hero list`, () => { it(`selects ${targetHero.name} from hero list`, () => {
let hero = element(by.cssContainingText('li span.badge', targetHero.id.toString())); const hero = element(by.cssContainingText('li span.badge', targetHero.id.toString()));
hero.click(); hero.click();
// Nothing specific to expect other than lack of exceptions. // Nothing specific to expect other than lack of exceptions.
}); });
it(`has selected ${targetHero.name}`, () => { it(`has selected ${targetHero.name}`, () => {
let page = getPageElts(); const page = getPageElts();
let expectedText = `${targetHero.id} ${targetHero.name}`; const expectedText = `${targetHero.id} ${targetHero.name}`;
expect(page.selected.getText()).toBe(expectedText); expect(page.selected.getText()).toBe(expectedText);
}); });
it('shows selected hero details', async () => { it('shows selected hero details', async () => {
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase()); expect(hero.name).toEqual(targetHero.name.toUpperCase());
}); });
@ -94,17 +94,17 @@ function updateHeroTests() {
}); });
it(`shows updated hero name in details`, async () => { it(`shows updated hero name in details`, async () => {
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
let newName = targetHero.name + nameSuffix; const newName = targetHero.name + nameSuffix;
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newName.toUpperCase()); expect(hero.name).toEqual(newName.toUpperCase());
}); });
it(`shows updated hero name in list`, async () => { it(`shows updated hero name in list`, async () => {
let page = getPageElts(); const page = getPageElts();
let hero = Hero.fromString(await page.selected.getText()); const hero = Hero.fromString(await page.selected.getText());
let newName = targetHero.name + nameSuffix; const newName = targetHero.name + nameSuffix;
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newName); expect(hero.name).toEqual(newName);
}); });
@ -112,13 +112,13 @@ function updateHeroTests() {
} }
function addToHeroName(text: string): promise.Promise<void> { function addToHeroName(text: string): promise.Promise<void> {
let input = element(by.css('input')); const input = element(by.css('input'));
return input.sendKeys(text); return input.sendKeys(text);
} }
function expectHeading(hLevel: number, expectedText: string): void { function expectHeading(hLevel: number, expectedText: string): void {
let hTag = `h${hLevel}`; const hTag = `h${hLevel}`;
let hText = element(by.css(hTag)).getText(); const hText = element(by.css(hTag)).getText();
expect(hText).toEqual(expectedText, hTag); expect(hText).toEqual(expectedText, hTag);
} }

View File

@ -24,9 +24,9 @@ class Hero {
// Get hero id and name from the given detail element. // Get hero id and name from the given detail element.
static async fromDetail(detail: ElementFinder): Promise<Hero> { static async fromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div> // Get hero id from the first <div>
let id = await detail.all(by.css('div')).first().getText(); const id = await detail.all(by.css('div')).first().getText();
// Get name from the h2 // Get name from the h2
let name = await detail.element(by.css('h2')).getText(); const name = await detail.element(by.css('h2')).getText();
return { return {
id: +id.substr(id.indexOf(' ') + 1), id: +id.substr(id.indexOf(' ') + 1),
name: name.substr(0, name.lastIndexOf(' ')) name: name.substr(0, name.lastIndexOf(' '))
@ -55,12 +55,12 @@ function initialPageTests() {
}); });
it('has the right number of heroes', () => { it('has the right number of heroes', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.heroes.count()).toEqual(10); expect(page.heroes.count()).toEqual(10);
}); });
it('has no selected hero and no hero details', () => { it('has no selected hero and no hero details', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.selected.isPresent()).toBeFalsy('selected hero'); expect(page.selected.isPresent()).toBeFalsy('selected hero');
expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail'); expect(page.heroDetail.isPresent()).toBeFalsy('no hero detail');
}); });
@ -68,21 +68,21 @@ function initialPageTests() {
function selectHeroTests() { function selectHeroTests() {
it(`selects ${targetHero.name} from hero list`, () => { it(`selects ${targetHero.name} from hero list`, () => {
let hero = element(by.cssContainingText('li span.badge', targetHero.id.toString())); const hero = element(by.cssContainingText('li span.badge', targetHero.id.toString()));
hero.click(); hero.click();
// Nothing specific to expect other than lack of exceptions. // Nothing specific to expect other than lack of exceptions.
}); });
it(`has selected ${targetHero.name}`, () => { it(`has selected ${targetHero.name}`, () => {
let page = getPageElts(); const page = getPageElts();
let expectedText = `${targetHero.id} ${targetHero.name}`; const expectedText = `${targetHero.id} ${targetHero.name}`;
expect(page.selected.getText()).toBe(expectedText); expect(page.selected.getText()).toBe(expectedText);
}); });
it('shows selected hero details', async () => { it('shows selected hero details', async () => {
let page = getPageElts(); const page = getPageElts();
let message = getMessage(); const message = getMessage();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase()); expect(hero.name).toEqual(targetHero.name.toUpperCase());
// Message text contain id number matches the hero.id number // Message text contain id number matches the hero.id number
@ -98,17 +98,17 @@ function updateHeroTests() {
}); });
it(`shows updated hero name in details`, async () => { it(`shows updated hero name in details`, async () => {
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
let newName = targetHero.name + nameSuffix; const newName = targetHero.name + nameSuffix;
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newName.toUpperCase()); expect(hero.name).toEqual(newName.toUpperCase());
}); });
it(`shows updated hero name in list`, async () => { it(`shows updated hero name in list`, async () => {
let page = getPageElts(); const page = getPageElts();
let hero = Hero.fromString(await page.selected.getText()); const hero = Hero.fromString(await page.selected.getText());
let newName = targetHero.name + nameSuffix; const newName = targetHero.name + nameSuffix;
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newName); expect(hero.name).toEqual(newName);
}); });
@ -116,13 +116,13 @@ function updateHeroTests() {
} }
function addToHeroName(text: string): promise.Promise<void> { function addToHeroName(text: string): promise.Promise<void> {
let input = element(by.css('input')); const input = element(by.css('input'));
return input.sendKeys(text); return input.sendKeys(text);
} }
function expectHeading(hLevel: number, expectedText: string): void { function expectHeading(hLevel: number, expectedText: string): void {
let hTag = `h${hLevel}`; const hTag = `h${hLevel}`;
let hText = element(by.css(hTag)).getText(); const hText = element(by.css(hTag)).getText();
expect(hText).toEqual(expectedText, hTag); expect(hText).toEqual(expectedText, hTag);
} }
@ -135,7 +135,7 @@ function getPageElts() {
} }
function getMessage() { function getMessage() {
let hero = element(by.cssContainingText('li span.badge', targetHero.id.toString())); const hero = element(by.cssContainingText('li span.badge', targetHero.id.toString()));
hero.click(); hero.click();
return element.all(by.css('app-root > app-messages > div > div')).get(1); return element.all(by.css('app-root > app-messages > div > div')).get(1);
} }

View File

@ -25,9 +25,9 @@ class Hero {
// Get hero id and name from the given detail element. // Get hero id and name from the given detail element.
static async fromDetail(detail: ElementFinder): Promise<Hero> { static async fromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div> // Get hero id from the first <div>
let id = await detail.all(by.css('div')).first().getText(); const id = await detail.all(by.css('div')).first().getText();
// Get name from the h2 // Get name from the h2
let name = await detail.element(by.css('h2')).getText(); const name = await detail.element(by.css('h2')).getText();
return { return {
id: +id.substr(id.indexOf(' ') + 1), id: +id.substr(id.indexOf(' ') + 1),
name: name.substr(0, name.lastIndexOf(' ')) name: name.substr(0, name.lastIndexOf(' '))
@ -40,7 +40,7 @@ describe('Tutorial part 5', () => {
beforeAll(() => browser.get('')); beforeAll(() => browser.get(''));
function getPageElts() { function getPageElts() {
let navElts = element.all(by.css('app-root nav a')); const navElts = element.all(by.css('app-root nav a'));
return { return {
navElts, navElts,
@ -68,12 +68,12 @@ describe('Tutorial part 5', () => {
const expectedViewNames = ['Dashboard', 'Heroes']; const expectedViewNames = ['Dashboard', 'Heroes'];
it(`has views ${expectedViewNames}`, () => { it(`has views ${expectedViewNames}`, () => {
let viewNames = getPageElts().navElts.map((el: ElementFinder) => el.getText()); const viewNames = getPageElts().navElts.map((el: ElementFinder) => el.getText());
expect(viewNames).toEqual(expectedViewNames); expect(viewNames).toEqual(expectedViewNames);
}); });
it('has dashboard as the active view', () => { it('has dashboard as the active view', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.appDashboard.isPresent()).toBeTruthy(); expect(page.appDashboard.isPresent()).toBeTruthy();
}); });
@ -84,7 +84,7 @@ describe('Tutorial part 5', () => {
beforeAll(() => browser.get('')); beforeAll(() => browser.get(''));
it('has top heroes', () => { it('has top heroes', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.topHeroes.count()).toEqual(4); expect(page.topHeroes.count()).toEqual(4);
}); });
@ -94,7 +94,7 @@ describe('Tutorial part 5', () => {
it(`saves and shows ${newHeroName} in Dashboard`, () => { it(`saves and shows ${newHeroName} in Dashboard`, () => {
element(by.buttonText('go back')).click(); element(by.buttonText('go back')).click();
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(newHeroName); expect(targetHeroElt.getText()).toEqual(newHeroName);
}); });
@ -106,7 +106,7 @@ describe('Tutorial part 5', () => {
it('can switch to Heroes view', () => { it('can switch to Heroes view', () => {
getPageElts().appHeroesHref.click(); getPageElts().appHeroesHref.click();
let page = getPageElts(); const page = getPageElts();
expect(page.appHeroes.isPresent()).toBeTruthy(); expect(page.appHeroes.isPresent()).toBeTruthy();
expect(page.allHeroes.count()).toEqual(10, 'number of heroes'); expect(page.allHeroes.count()).toEqual(10, 'number of heroes');
}); });
@ -114,9 +114,9 @@ describe('Tutorial part 5', () => {
it('can route to hero details', async () => { it('can route to hero details', async () => {
getHeroLiEltById(targetHero.id).click(); getHeroLiEltById(targetHero.id).click();
let page = getPageElts(); const page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase()); expect(hero.name).toEqual(targetHero.name.toUpperCase());
}); });
@ -125,20 +125,20 @@ describe('Tutorial part 5', () => {
it(`shows ${newHeroName} in Heroes list`, () => { it(`shows ${newHeroName} in Heroes list`, () => {
element(by.buttonText('go back')).click(); element(by.buttonText('go back')).click();
let expectedText = `${targetHero.id} ${newHeroName}`; const expectedText = `${targetHero.id} ${newHeroName}`;
expect(getHeroLiEltById(targetHero.id).getText()).toEqual(expectedText); expect(getHeroLiEltById(targetHero.id).getText()).toEqual(expectedText);
}); });
}); });
async function dashboardSelectTargetHero() { async function dashboardSelectTargetHero() {
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(targetHero.name); expect(targetHeroElt.getText()).toEqual(targetHero.name);
targetHeroElt.click(); targetHeroElt.click();
let page = getPageElts(); const page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase()); expect(hero.name).toEqual(targetHero.name.toUpperCase());
} }
@ -147,8 +147,8 @@ describe('Tutorial part 5', () => {
// Assumes that the current view is the hero details view. // Assumes that the current view is the hero details view.
addToHeroName(nameSuffix); addToHeroName(nameSuffix);
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newHeroName.toUpperCase()); expect(hero.name).toEqual(newHeroName.toUpperCase());
} }
@ -156,17 +156,17 @@ describe('Tutorial part 5', () => {
}); });
function addToHeroName(text: string): promise.Promise<void> { function addToHeroName(text: string): promise.Promise<void> {
let input = element(by.css('input')); const input = element(by.css('input'));
return input.sendKeys(text); return input.sendKeys(text);
} }
function expectHeading(hLevel: number, expectedText: string): void { function expectHeading(hLevel: number, expectedText: string): void {
let hTag = `h${hLevel}`; const hTag = `h${hLevel}`;
let hText = element(by.css(hTag)).getText(); const hText = element(by.css(hTag)).getText();
expect(hText).toEqual(expectedText, hTag); expect(hText).toEqual(expectedText, hTag);
} }
function getHeroLiEltById(id: number) { function getHeroLiEltById(id: number) {
let spanForId = element(by.cssContainingText('li span.badge', id.toString())); const spanForId = element(by.cssContainingText('li span.badge', id.toString()));
return spanForId.element(by.xpath('..')); return spanForId.element(by.xpath('..'));
} }

View File

@ -24,17 +24,17 @@ class Hero {
// Hero from hero list <li> element. // Hero from hero list <li> element.
static async fromLi(li: ElementFinder): Promise<Hero> { static async fromLi(li: ElementFinder): Promise<Hero> {
let stringsFromA = await li.all(by.css('a')).getText(); const stringsFromA = await li.all(by.css('a')).getText();
let strings = stringsFromA[0].split(' '); const strings = stringsFromA[0].split(' ');
return { id: +strings[0], name: strings[1] }; return { id: +strings[0], name: strings[1] };
} }
// Hero id and name from the given detail element. // Hero id and name from the given detail element.
static async fromDetail(detail: ElementFinder): Promise<Hero> { static async fromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div> // Get hero id from the first <div>
let id = await detail.all(by.css('div')).first().getText(); const id = await detail.all(by.css('div')).first().getText();
// Get name from the h2 // Get name from the h2
let name = await detail.element(by.css('h2')).getText(); const name = await detail.element(by.css('h2')).getText();
return { return {
id: +id.substr(id.indexOf(' ') + 1), id: +id.substr(id.indexOf(' ') + 1),
name: name.substr(0, name.lastIndexOf(' ')) name: name.substr(0, name.lastIndexOf(' '))
@ -47,7 +47,7 @@ describe('Tutorial part 6', () => {
beforeAll(() => browser.get('')); beforeAll(() => browser.get(''));
function getPageElts() { function getPageElts() {
let navElts = element.all(by.css('app-root nav a')); const navElts = element.all(by.css('app-root nav a'));
return { return {
navElts, navElts,
@ -80,12 +80,12 @@ describe('Tutorial part 6', () => {
const expectedViewNames = ['Dashboard', 'Heroes']; const expectedViewNames = ['Dashboard', 'Heroes'];
it(`has views ${expectedViewNames}`, () => { it(`has views ${expectedViewNames}`, () => {
let viewNames = getPageElts().navElts.map((el: ElementFinder) => el.getText()); const viewNames = getPageElts().navElts.map((el: ElementFinder) => el.getText());
expect(viewNames).toEqual(expectedViewNames); expect(viewNames).toEqual(expectedViewNames);
}); });
it('has dashboard as the active view', () => { it('has dashboard as the active view', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.appDashboard.isPresent()).toBeTruthy(); expect(page.appDashboard.isPresent()).toBeTruthy();
}); });
@ -96,7 +96,7 @@ describe('Tutorial part 6', () => {
beforeAll(() => browser.get('')); beforeAll(() => browser.get(''));
it('has top heroes', () => { it('has top heroes', () => {
let page = getPageElts(); const page = getPageElts();
expect(page.topHeroes.count()).toEqual(4); expect(page.topHeroes.count()).toEqual(4);
}); });
@ -108,7 +108,7 @@ describe('Tutorial part 6', () => {
element(by.buttonText('go back')).click(); element(by.buttonText('go back')).click();
browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(targetHero.name); expect(targetHeroElt.getText()).toEqual(targetHero.name);
}); });
@ -120,7 +120,7 @@ describe('Tutorial part 6', () => {
element(by.buttonText('save')).click(); element(by.buttonText('save')).click();
browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(newHeroName); expect(targetHeroElt.getText()).toEqual(newHeroName);
}); });
@ -132,7 +132,7 @@ describe('Tutorial part 6', () => {
it('can switch to Heroes view', () => { it('can switch to Heroes view', () => {
getPageElts().appHeroesHref.click(); getPageElts().appHeroesHref.click();
let page = getPageElts(); const page = getPageElts();
expect(page.appHeroes.isPresent()).toBeTruthy(); expect(page.appHeroes.isPresent()).toBeTruthy();
expect(page.allHeroes.count()).toEqual(10, 'number of heroes'); expect(page.allHeroes.count()).toEqual(10, 'number of heroes');
}); });
@ -140,9 +140,9 @@ describe('Tutorial part 6', () => {
it('can route to hero details', async () => { it('can route to hero details', async () => {
getHeroLiEltById(targetHero.id).click(); getHeroLiEltById(targetHero.id).click();
let page = getPageElts(); const page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase()); expect(hero.name).toEqual(targetHero.name.toUpperCase());
}); });
@ -152,7 +152,7 @@ describe('Tutorial part 6', () => {
it(`shows ${newHeroName} in Heroes list`, () => { it(`shows ${newHeroName} in Heroes list`, () => {
element(by.buttonText('save')).click(); element(by.buttonText('save')).click();
browser.waitForAngular(); browser.waitForAngular();
let expectedText = `${targetHero.id} ${newHeroName}`; const expectedText = `${targetHero.id} ${newHeroName}`;
expect(getHeroAEltById(targetHero.id).getText()).toEqual(expectedText); expect(getHeroAEltById(targetHero.id).getText()).toEqual(expectedText);
}); });
@ -179,8 +179,8 @@ describe('Tutorial part 6', () => {
element(by.css('input')).sendKeys(addedHeroName); element(by.css('input')).sendKeys(addedHeroName);
element(by.buttonText('add')).click(); element(by.buttonText('add')).click();
let page = getPageElts(); const page = getPageElts();
let heroesAfter = await toHeroArray(page.allHeroes); const heroesAfter = await toHeroArray(page.allHeroes);
expect(heroesAfter.length).toEqual(numHeroes + 1, 'number of heroes'); expect(heroesAfter.length).toEqual(numHeroes + 1, 'number of heroes');
expect(heroesAfter.slice(0, numHeroes)).toEqual(heroesBefore, 'Old heroes are still there'); expect(heroesAfter.slice(0, numHeroes)).toEqual(heroesBefore, 'Old heroes are still there');
@ -233,34 +233,34 @@ describe('Tutorial part 6', () => {
it(`continues search with 'e' and gets ${targetHero.name}`, async () => { it(`continues search with 'e' and gets ${targetHero.name}`, async () => {
getPageElts().searchBox.sendKeys('n'); getPageElts().searchBox.sendKeys('n');
browser.sleep(1000); browser.sleep(1000);
let page = getPageElts(); const page = getPageElts();
expect(page.searchResults.count()).toBe(1); expect(page.searchResults.count()).toBe(1);
let hero = page.searchResults.get(0); const hero = page.searchResults.get(0);
expect(hero.getText()).toEqual(targetHero.name); expect(hero.getText()).toEqual(targetHero.name);
}); });
it(`navigates to ${targetHero.name} details view`, async () => { it(`navigates to ${targetHero.name} details view`, async () => {
let hero = getPageElts().searchResults.get(0); const hero = getPageElts().searchResults.get(0);
expect(hero.getText()).toEqual(targetHero.name); expect(hero.getText()).toEqual(targetHero.name);
hero.click(); hero.click();
let page = getPageElts(); const page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero2 = await Hero.fromDetail(page.heroDetail); const hero2 = await Hero.fromDetail(page.heroDetail);
expect(hero2.id).toEqual(targetHero.id); expect(hero2.id).toEqual(targetHero.id);
expect(hero2.name).toEqual(targetHero.name.toUpperCase()); expect(hero2.name).toEqual(targetHero.name.toUpperCase());
}); });
}); });
async function dashboardSelectTargetHero() { async function dashboardSelectTargetHero() {
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex); const targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(targetHero.name); expect(targetHeroElt.getText()).toEqual(targetHero.name);
targetHeroElt.click(); targetHeroElt.click();
browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6
let page = getPageElts(); const page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail'); expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase()); expect(hero.name).toEqual(targetHero.name.toUpperCase());
} }
@ -269,8 +269,8 @@ describe('Tutorial part 6', () => {
// Assumes that the current view is the hero details view. // Assumes that the current view is the hero details view.
addToHeroName(nameSuffix); addToHeroName(nameSuffix);
let page = getPageElts(); const page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail); const hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id); expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newHeroName.toUpperCase()); expect(hero.name).toEqual(newHeroName.toUpperCase());
} }
@ -278,28 +278,28 @@ describe('Tutorial part 6', () => {
}); });
function addToHeroName(text: string): promise.Promise<void> { function addToHeroName(text: string): promise.Promise<void> {
let input = element(by.css('input')); const input = element(by.css('input'));
return input.sendKeys(text); return input.sendKeys(text);
} }
function expectHeading(hLevel: number, expectedText: string): void { function expectHeading(hLevel: number, expectedText: string): void {
let hTag = `h${hLevel}`; const hTag = `h${hLevel}`;
let hText = element(by.css(hTag)).getText(); const hText = element(by.css(hTag)).getText();
expect(hText).toEqual(expectedText, hTag); expect(hText).toEqual(expectedText, hTag);
} }
function getHeroAEltById(id: number): ElementFinder { function getHeroAEltById(id: number): ElementFinder {
let spanForId = element(by.cssContainingText('li span.badge', id.toString())); const spanForId = element(by.cssContainingText('li span.badge', id.toString()));
return spanForId.element(by.xpath('..')); return spanForId.element(by.xpath('..'));
} }
function getHeroLiEltById(id: number): ElementFinder { function getHeroLiEltById(id: number): ElementFinder {
let spanForId = element(by.cssContainingText('li span.badge', id.toString())); const spanForId = element(by.cssContainingText('li span.badge', id.toString()));
return spanForId.element(by.xpath('../..')); return spanForId.element(by.xpath('../..'));
} }
async function toHeroArray(allHeroes: ElementArrayFinder): Promise<Hero[]> { async function toHeroArray(allHeroes: ElementArrayFinder): Promise<Hero[]> {
let promisedHeroes = await allHeroes.map(Hero.fromLi); const promisedHeroes = await allHeroes.map(Hero.fromLi);
// The cast is necessary to get around issuing with the signature of Promise.all() // The cast is necessary to get around issuing with the signature of Promise.all()
return Promise.all(promisedHeroes) as Promise<any>; return Promise.all(promisedHeroes) as Promise<any>;
} }

View File

@ -6,10 +6,10 @@ describe('Two-way binding e2e tests', () => {
browser.get(''); browser.get('');
}); });
let minusButton = element.all(by.css('button')).get(0); const minusButton = element.all(by.css('button')).get(0);
let plusButton = element.all(by.css('button')).get(1); const plusButton = element.all(by.css('button')).get(1);
let minus2Button = element.all(by.css('button')).get(2); const minus2Button = element.all(by.css('button')).get(2);
let plus2Button = element.all(by.css('button')).get(3); const plus2Button = element.all(by.css('button')).get(3);
it('should display Two-way Binding', () => { it('should display Two-way Binding', () => {
expect(element(by.css('h1')).getText()).toEqual('Two-way Binding'); expect(element(by.css('h1')).getText()).toEqual('Two-way Binding');

View File

@ -57,7 +57,7 @@ describe('Lazy Loading AngularJS Tests', () => {
// Run the protractor pre-bootstrap logic and resumeBootstrap // Run the protractor pre-bootstrap logic and resumeBootstrap
// Based on https://github.com/angular/protractor/blob/5.3.0/lib/browser.ts#L950-L969 // Based on https://github.com/angular/protractor/blob/5.3.0/lib/browser.ts#L950-L969
{ {
let moduleNames = []; const moduleNames = [];
for (const {name, script, args} of browser.mockModules_) { for (const {name, script, args} of browser.mockModules_) {
moduleNames.push(name); moduleNames.push(name);
await browser.executeScriptWithDescription(script, 'add mock module ' + name, ...args); await browser.executeScriptWithDescription(script, 'add mock module ' + name, ...args);

View File

@ -2,7 +2,7 @@
describe('Phone', () => { describe('Phone', () => {
let $httpBackend: angular.IHttpBackendService; let $httpBackend: angular.IHttpBackendService;
let Phone: any; let Phone: any;
let phonesData = [ const phonesData = [
{name: 'Phone X'}, {name: 'Phone X'},
{name: 'Phone Y'}, {name: 'Phone Y'},
{name: 'Phone Z'} {name: 'Phone Z'}
@ -31,7 +31,7 @@ describe('Phone', () => {
}); });
it('should fetch the phones data from `/phones/phones.json`', () => { it('should fetch the phones data from `/phones/phones.json`', () => {
let phones = Phone.query(); const phones = Phone.query();
expect(phones).toEqual([]); expect(phones).toEqual([]);

View File

@ -9,7 +9,7 @@ describe('phoneDetail', () => {
describe('PhoneDetailController', () => { describe('PhoneDetailController', () => {
let $httpBackend: angular.IHttpBackendService; let $httpBackend: angular.IHttpBackendService;
let ctrl: any; let ctrl: any;
let xyzPhoneData = { const xyzPhoneData = {
name: 'phone xyz', name: 'phone xyz',
images: ['image/url1.png', 'image/url2.png'] images: ['image/url1.png', 'image/url2.png']
}; };

View File

@ -6,7 +6,7 @@ class PhoneDetailController {
static $inject = ['$routeParams', 'Phone']; static $inject = ['$routeParams', 'Phone'];
constructor($routeParams: angular.route.IRouteParamsService, Phone: any) { constructor($routeParams: angular.route.IRouteParamsService, Phone: any) {
let phoneId = $routeParams.phoneId; const phoneId = $routeParams.phoneId;
this.phone = Phone.get({phoneId}, (phone: any) => { this.phone = Phone.get({phoneId}, (phone: any) => {
this.setImage(phone.images[0]); this.setImage(phone.images[0]);
}); });

View File

@ -29,8 +29,8 @@ describe('PhoneCat Application', () => {
}); });
it('should filter the phone list as a user types into the search box', () => { it('should filter the phone list as a user types into the search box', () => {
let phoneList = element.all(by.repeater('phone in $ctrl.phones')); const phoneList = element.all(by.repeater('phone in $ctrl.phones'));
let query = element(by.model('$ctrl.query')); const query = element(by.model('$ctrl.query'));
waitForCount(phoneList, 20); waitForCount(phoneList, 20);
expect(phoneList.count()).toBe(20); expect(phoneList.count()).toBe(20);
@ -46,10 +46,10 @@ describe('PhoneCat Application', () => {
}); });
it('should be possible to control phone order via the drop-down menu', () => { it('should be possible to control phone order via the drop-down menu', () => {
let queryField = element(by.model('$ctrl.query')); const queryField = element(by.model('$ctrl.query'));
let orderSelect = element(by.model('$ctrl.orderProp')); const orderSelect = element(by.model('$ctrl.orderProp'));
let nameOption = orderSelect.element(by.css('option[value="name"]')); const nameOption = orderSelect.element(by.css('option[value="name"]'));
let phoneNameColumn = element.all(by.repeater('phone in $ctrl.phones').column('phone.name')); const phoneNameColumn = element.all(by.repeater('phone in $ctrl.phones').column('phone.name'));
function getNames() { function getNames() {
return phoneNameColumn.map((elem: ElementFinder) => elem.getText()); return phoneNameColumn.map((elem: ElementFinder) => elem.getText());
@ -72,14 +72,14 @@ describe('PhoneCat Application', () => {
}); });
it('should render phone specific links', () => { it('should render phone specific links', () => {
let phoneList = element.all(by.repeater('phone in $ctrl.phones')); const phoneList = element.all(by.repeater('phone in $ctrl.phones'));
let query = element(by.model('$ctrl.query')); const query = element(by.model('$ctrl.query'));
query.sendKeys('nexus'); query.sendKeys('nexus');
waitForCount(phoneList, 1); waitForCount(phoneList, 1);
let nexusPhone = phoneList.first(); const nexusPhone = phoneList.first();
let detailLink = nexusPhone.all(by.css('a')).first(); const detailLink = nexusPhone.all(by.css('a')).first();
detailLink.click(); detailLink.click();
expect(browser.getLocationAbsUrl()).toBe('/phones/nexus-s'); expect(browser.getLocationAbsUrl()).toBe('/phones/nexus-s');
@ -98,14 +98,14 @@ describe('PhoneCat Application', () => {
}); });
it('should display the first phone image as the main phone image', () => { it('should display the first phone image as the main phone image', () => {
let mainImage = element(by.css('img.phone.selected')); const mainImage = element(by.css('img.phone.selected'));
expect(mainImage.getAttribute('src')).toMatch(/img\/phones\/nexus-s.0.jpg/); expect(mainImage.getAttribute('src')).toMatch(/img\/phones\/nexus-s.0.jpg/);
}); });
it('should swap the main image when clicking on a thumbnail image', () => { it('should swap the main image when clicking on a thumbnail image', () => {
let mainImage = element(by.css('img.phone.selected')); const mainImage = element(by.css('img.phone.selected'));
let thumbnails = element.all(by.css('.phone-thumbs img')); const thumbnails = element.all(by.css('.phone-thumbs img'));
thumbnails.get(2).click(); thumbnails.get(2).click();
expect(mainImage.getAttribute('src')).toMatch(/img\/phones\/nexus-s.2.jpg/); expect(mainImage.getAttribute('src')).toMatch(/img\/phones\/nexus-s.2.jpg/);

View File

@ -6,7 +6,7 @@ import { Phone, PhoneData } from './phone.service';
describe('Phone', () => { describe('Phone', () => {
let phone: Phone; let phone: Phone;
let phonesData: PhoneData[] = [ const phonesData: PhoneData[] = [
{name: 'Phone X', snippet: '', images: []}, {name: 'Phone X', snippet: '', images: []},
{name: 'Phone Y', snippet: '', images: []}, {name: 'Phone Y', snippet: '', images: []},
{name: 'Phone Z', snippet: '', images: []} {name: 'Phone Z', snippet: '', images: []}

View File

@ -9,7 +9,7 @@ class PhoneDetailController {
static $inject = ['$routeParams', 'phone']; static $inject = ['$routeParams', 'phone'];
constructor($routeParams: angular.route.IRouteParamsService, phone: Phone) { constructor($routeParams: angular.route.IRouteParamsService, phone: Phone) {
let phoneId = $routeParams.phoneId; const phoneId = $routeParams.phoneId;
phone.get(phoneId).subscribe(data => { phone.get(phoneId).subscribe(data => {
this.phone = data; this.phone = data;
this.setImage(data.images[0]); this.setImage(data.images[0]);

Some files were not shown because too many files have changed in this diff Show More