<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Why E2E &#8211; Sibeesh Passion</title>
	<atom:link href="https://www.sibeeshpassion.com/tag/why-e2e/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Mon, 09 Jul 2018 04:59:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Why E2E &#8211; Sibeesh Passion</title>
	<link>https://www.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>End to End (E2E) Tests in Angular Application Using Protractor</title>
		<link>https://www.sibeeshpassion.com/end-to-end-e2e-tests-in-angular-application-using-protractor/</link>
					<comments>https://www.sibeeshpassion.com/end-to-end-e2e-tests-in-angular-application-using-protractor/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 08 Jul 2018 15:25:34 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[angular-cli]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[E2E]]></category>
		<category><![CDATA[End to End Test]]></category>
		<category><![CDATA[Protractor]]></category>
		<category><![CDATA[Why E2E]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13062</guid>

					<description><![CDATA[[toc] Introduction In this article, we will learn how we can create an end to end tests (e2e) for our Angular application. We will be using an existing end-to-end testing framework, which is nothing but, Protractor. Protractor runs your tests against your application running in a real browser, in the same way, your user may perform the actions. I will be using an existing application which is available in my GitHub profile. The same can be available in the source code section. Please do share your feedback with me. I hope you will like this article. Let&#8217;s start coding. Source Code The [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this article, we will learn how we can create an end to end tests (e2e) for our <a href="https://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> application. We will be using an existing end-to-end testing framework, which is nothing but, Protractor. Protractor runs your tests against your application running in a real browser, in the same way, your user may perform the actions. I will be using an existing application which is available in my <a href="https://github.com/sibeeshvenu">GitHub</a> profile. The same can be available in the source code section. Please do share your feedback with me. I hope you will like this article. Let&#8217;s start coding.</p>
<h2>Source Code</h2>
<p>The source code can be found <a href="https://github.com/SibeeshVenu/ng5">here</a>. Please clone this repository before you start.</p>
<h2>Importance of End to End Testing</h2>
<p>Some of you might have already started writing an end to end testing for your application, and you may be knowing how important that is. Here in this section, I will list down the key benefits of an end to end testing.</p>
<ul>
<li>End to end testing tests the complete flow or the action. For example, a complete login process can be treated as one end to end testing. Basically, it tests a specific functionality.</li>
<li>It doesn&#8217;t improve the code quality as does in Unit testing. Unit testing is a different topic, and an end to end testing and unit testing are completely different.</li>
<li>As I said earlier, an end to end testing run tests on the browser, so it tests your application live, with some real data.</li>
<li>You can easily find out if any functionalities are broken because of your recent changes or implementation</li>
</ul>
<h2>Basic overview</h2>
<p>If you have already cloned the application, you should be able to see a folder e2e in your application code, open that folder. You can see 3 files as below.</p>
<ul>
<li>tsconfig.e2e.json</li>
<li>app.po.ts</li>
<li>app.e2e-spec.ts</li>
</ul>
<p>Here <em>tsconfig.e2e.json</em> is the configuration file, if you open that file, you can see that the file is been extended from <em>tsconfig.json. </em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/e2e",
    "baseUrl": "./",
    "module": "commonjs",
    "target": "es5",
    "types": [
      "jasmine",
      "jasminewd2",
      "node"
    ]
  }
}
</pre>
<p><em>app.po.ts </em>is the page object, this is really helpful and important. Here is the place, where we will write the codes to find out the elements on our page or view. So, in future, if you are changing the selectors of your element, your changes will impact only in this file, so that you don&#8217;t need to change anything in your tests. Isn&#8217;t that handy? By default, this file will have the codes as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { browser, by, element } from 'protractor';

export class AppPage {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('app-root h1')).getText();
  }
}
</pre>
<p>As you can see, on the first line, we are importing browser, by, an element from protractor.</p>
<ol>
<li>browser, is for interacting with the browser</li>
<li>by, is for finding the element by CSS or any other function</li>
<li>element, is for converting the selected element</li>
</ol>
<p>Here in this line, element(by.css(&#8216;app-root h1&#8217;)).getText(), like you have already guessed, we are just finding an element with the selector &#8216;app-root h1&#8217;</p>
<p><em>app.e2e-spec.ts </em> is the tests holder. We will be writing all of our tests here.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { AppPage } from './app.po';

describe('my-angular5-app App', () =&gt; {
  let page: AppPage;

  beforeEach(() =&gt; {
    page = new AppPage();
  });

  it('should display welcome message', () =&gt; {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to ng5!');
  });
});
</pre>
<p>The first thing we do is, importing the page, in this case, AppPage. This will be very easy for you if you have already written any <a href="https://sibeeshpassion.com/category/unit-testing/">unit test</a> cases using <a href="https://sibeeshpassion.com/category/unit-testing/jasmine-framework/">jasmine</a>. If you are not sure about how you can write the unit tests, I recommend you to visit this <a href="https://sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/">link</a>.</p>
<p>Once we import the page, we are declaring an object and initialize the same with an AppPage instance in <em>beforeEach</em> function, so that the code can be executed before each test runs.</p>
<p>And in our first test, we are just confirming that the title is &#8216;Welcome to app&#8217; by getting the value from our page object by calling <em>page.getParagraphText(). </em></p>
<h2>Creating Login Component</h2>
<p>As you all know, a component will have two files by default.</p>
<ul>
<li>login.component.html</li>
<li>login.component.ts</li>
</ul>
<h3>login.component.html</h3>
<p>Let&#8217;s write some HTML code for our component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container" style="margin-top:100px;"&gt;
  &lt;div class="row justify-content-center align-items-center"&gt;
    &lt;div class="col-lg-4 col-sm-4 center-block "&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Login here&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;div class="signup-fields"&gt;
            &lt;form id="loginForm"[formGroup]="form" (ngSubmit)="login()"&gt;
              &lt;div class="form-group"&gt;
                &lt;input name="email" class="form-control" matInput type="email" placeholder="Email" formControlName="email" /&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                &lt;input name="password" class="form-control" matInput type="password" placeholder="Password" formControlName="password" /&gt;
              &lt;/div&gt;
              &lt;div&gt;
                &lt;button id="btnSubmit" mat-raised-button type="submit" color="primary"&gt;Login&lt;/button&gt;
              &lt;/div&gt;
            &lt;/form&gt;
          &lt;/div&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<h3>login.component.ts</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form;
  constructor(private fb: FormBuilder,
    private myRoute: Router,
    private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

  ngOnInit() {
  }

  login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }

}
</pre>
<p>If you run the application, you can see that we are accepting the form only if we give relevant values to the fields, if not given, the form will be invalid. In our next step, we will write an end to end test for this functionality. Sounds good?</p>
<h2>Write end to end tests for Login component</h2>
<p>To get started, let us create two files as below.</p>
<ol>
<li>login.po.ts</li>
<li>login.e2e-spec.ts</li>
</ol>
<p>Now let us define our page and some functions in login.po.ts.</p>
<h3>Set up login.po.ts</h3>
<p>Open the file and write some code as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { browser, by, element } from 'protractor';

export class LoginPage {
    navigateTo(){
        return browser.get('/login');
    }
}</pre>
<p>Now we will write the codes to find the email and password text boxes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">getEmailTextbox() {
 return element(by.name('email'));
}

getPasswordTextbox() {
 return element(by.name('password'));
}</pre>
<h3>Set up login.e2e-spec.ts</h3>
<p>It is time to set up our spec file before we start writing the tests.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { LoginPage } from './login.po';

describe('Login tests', () =&gt; {
    let page: LoginPage;

    beforeEach(() =&gt; {
        page = new LoginPage();
        page.navigateTo();        
    });
});</pre>
<p>We have imported our login page and initialized the same. It is time to write the tests now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">it('Login form should be valid', () =&gt; {
 page.getEmailTextbox().sendKeys('info@sibeeshpassion.com');
 page.getPasswordTextbox().sendKeys('1234');

 let form = page.getForm().getAttribute('class');

 expect(form).toContain('ng-valid');
});</pre>
<p>Here what we are doing is, set the values to our text boxes by using sendKeys function and then find the class attribute of our form, so that we can check whether it is valid or not. If the form is valid, the form will be having the class as ng-valid, if not, it will have ng-invalid class.</p>
<h2>Run end to end test</h2>
<p>Running end to end test is as easy as falling off a log. As we are using Angular CLI, all we have to do is run the command <em>ng e2e. </em> This will be set in our <em>package.json </em>file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }</pre>
<p>let us run <em>ng e2e </em>now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\My Projects\ng5&gt; ng e2e</pre>
<p>If everything goes well, your application should open in a browser and test the functionality. You will also get a message saying &#8220;Chrome is being controlled by automated test software&#8221;.</p>
<div id="attachment_13064" style="width: 453px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/07/ng-e2e-browser-output.jpg"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-13064" class="size-full wp-image-13064" src="https://sibeeshpassion.com/wp-content/uploads/2018/07/ng-e2e-browser-output.jpg" alt="ng e2e browser output" width="443" height="180" srcset="/wp-content/uploads/2018/07/ng-e2e-browser-output.jpg 443w, /wp-content/uploads/2018/07/ng-e2e-browser-output-300x122.jpg 300w, /wp-content/uploads/2018/07/ng-e2e-browser-output-400x163.jpg 400w" sizes="(max-width: 443px) 100vw, 443px" /></a><p id="caption-attachment-13064" class="wp-caption-text">ng e2e browser output</p></div>
<p>And in your terminal console, you should see an output saying all of your tests are passed.</p>
<div id="attachment_13065" style="width: 644px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/07/Automated-test-output-e1531050755639.jpg"><img decoding="async" aria-describedby="caption-attachment-13065" class="size-full wp-image-13065" src="https://sibeeshpassion.com/wp-content/uploads/2018/07/Automated-test-output-e1531050755639.jpg" alt="Automated test output" width="634" height="187" /></a><p id="caption-attachment-13065" class="wp-caption-text">Automated test output</p></div>
<h2>Writing a few more tests</h2>
<p>Let us write a few more tests to check some other functionalities.</p>
<h3>Check form is invalid</h3>
<p>To check the form is invalid or not, we need to pass some invalid data to the form. The final test should be as follows.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">it('Login form should be invalid', () =&gt; {
 page.getEmailTextbox().sendKeys('');
 page.getPasswordTextbox().sendKeys('');

 let form = page.getForm().getAttribute('class');

 expect(form).toContain('ng-invalid');
});</pre>
<h3>Check whether the value is been saved to local storage</h3>
<p>You might have already looked at what is the functionality we are doing when we click the login button in our application. For now, we are just saving the email value to the local storage. Below is the function which gets called when we click the login button.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }</pre>
<p>And this is the sendToken method in out AuthService.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">sendToken(token: string) {
    localStorage.setItem("LoggedInUser", token)
 }</pre>
<p>Now, we are going to write an automated test for this functionality. First, let us add a function which returns submit button in login.po.ts.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">getSubmitButton() {
 return element(by.css('#btnSubmit'));
}</pre>
<p>Now, write the test as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">it('Should set email value to local storage', () =&gt; {
 page.getEmailTextbox().sendKeys('info@sibeeshpassion.com');
 page.getPasswordTextbox().sendKeys('1234');

 page.getSubmitButton().click();

 let valLocalStorage = browser.executeScript("return window.localStorage.getItem('LoggedInUser');");
 expect(valLocalStorage).toEqual('info@sibeeshpassion.com');
});</pre>
<p>As you can see that, we are actually setting some valid data to the form and triggering the click event of our button, and the value of the email text box is being saved to the <a href="https://sibeeshpassion.com/?s=local+storage">localStorage</a>. In our test, we are checking the value of the localStorage by executing the script <em>browser.executeScript(&#8220;return window.localStorage.getItem(&#8216;LoggedInUser&#8217;);&#8221;). </em>We should get an output as below if everything is fine.</p>
<div id="attachment_13066" style="width: 644px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/07/locaStorage-in-Protractor.jpg"><img decoding="async" aria-describedby="caption-attachment-13066" class="size-full wp-image-13066" src="https://sibeeshpassion.com/wp-content/uploads/2018/07/locaStorage-in-Protractor.jpg" alt="locaStorage in Protractor" width="634" height="252" srcset="/wp-content/uploads/2018/07/locaStorage-in-Protractor.jpg 634w, /wp-content/uploads/2018/07/locaStorage-in-Protractor-300x119.jpg 300w, /wp-content/uploads/2018/07/locaStorage-in-Protractor-400x159.jpg 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-13066" class="wp-caption-text">locaStorage in Protractor</p></div>
<h2><span id="conclusion_1"><span id="conclusion">Conclusion</span></span></h2>
<p>Thanks a lot for reading. I will come back with another post on the same topic very soon. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/end-to-end-e2e-tests-in-angular-application-using-protractor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
