Skip to content

Commit

Permalink
docs: testing - highlight dispatchEvent
Browse files Browse the repository at this point in the history
  • Loading branch information
wardbell committed Mar 13, 2018
1 parent 21e44c6 commit c47990d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -197,20 +197,21 @@ function heroModuleSetup() {

// #docregion title-case-pipe
it('should convert hero name to Title Case', () => {
const inputName = 'quick BROWN fox';
const titleCaseName = 'Quick Brown Fox';
const { nameInput, nameDisplay } = page;
// get the name's input and display elements from the DOM
const hostElement = fixture.nativeElement;
const nameInput: HTMLInputElement = hostElement.querySelector('input');
const nameDisplay: HTMLElement = hostElement.querySelector('span');

// simulate user entering new name into the input box
nameInput.value = inputName;
// simulate user entering a new name into the input box
nameInput.value = 'quick BROWN fOx';

// dispatch a DOM event so that Angular learns of input value change.
nameInput.dispatchEvent(newEvent('input'));

// Tell Angular to update the output span through the title pipe
// Tell Angular to update the display binding through the title pipe
fixture.detectChanges();

expect(nameDisplay.textContent).toBe(titleCaseName);
expect(nameDisplay.textContent).toBe('Quick Brown Fox');
});
// #enddocregion title-case-pipe
// #enddocregion selected-tests
Expand Down
18 changes: 18 additions & 0 deletions aio/content/guide/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,24 @@ There is no harm in calling `detectChanges()` more often than is strictly necess

<hr>

{@a dispatch-event}

#### Change an input value with _dispatchEvent()_

To simulate user input, you can find the input element and set its `value` property.
Then call `fixture.detectChanges()` to trigger Angular's change detection.

This _almost works_.
Unfortunately, Angular doesn't know that the input element changed so it doesn't read the input element's `value` property and nothing happens.

You must make the input element raise its `input` event, using the `HTMLElement.dispatchEvent()` method.

The following example shows how to do this.

<code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="title-case-pipe" title="app/hero/hero-detail.component.spec.ts (pipe test)"></code-example>

<hr>

### Component with external files

The `BannerComponent` above is defined with an _inline template_ and _inline css_, specified in the `@Component.template` and `@Component.styles` properties respectively.
Expand Down

0 comments on commit c47990d

Please sign in to comment.