Macess  Hulk

Macess Hulk

1587461280

Using @Input() to Testing Components in Angular

When developing an Angular component that takes an input, you might decide to unit test the whole component. At least I hope you do!

For example, we have a component, ComponentUnderTest, in which we want to display upcased input… I know right: what a great use-case, every business owner needs that!

So, let’s say the ComponentUnderTest binds and displays input.

@Component({
  selector: 'component-under-test',
  template: '<div>{{ input }}</div>'
})
export class ComponentUnderTestComponent{

  @Input() input;

  processInput(): void {
    this.input = this.input.toUpperCase();
  }
}

To verify that processInput() correctly upcases our input, we can simply assign a test value to the input variable and assert that, after calling the method, the displayed input is in ALL CAPS.

  it('should show TEST INPUT', () => {
    component.input = 'test input';
    component.processInput();
    fixture.detectChanges();
    expect(fixture.nativeElement.querySelector('div').innerText).toEqual('TEST INPUT');
  });

Easy peasy! Right?

But by now, we need to manually call processInput() and until we call it, our input is still displayed in lousy lowercase.

Luckily, with Angular’s OnInit lifecycle hook, we can trigger our processInput() even before displaying anything. So let’s implement it and call processInput() in the corresponding method.

  ngOnInit(){
    this.processInput();
  }

Let’s run the tests!

Oh no! The tests fail!

Cannot read property ‘toUpperCase’ of undefined

Ah, of course, by the time toUpperCase() is called on the input in our ngOnInit() we have not even assigned any value to it yet.

When we actually embed our component in the production code, we would have set the value of input by binding the input in the component’s tag.

<component-under-test input=“some input”></component-under-test>

So let’s embed the ComponentUnderTest in a TestHostComponent. By actually having a host or parent component, we are able to pass in exactly the input we want for our test.

In our test, we can simply define this TestHostComponent, include it in the testing module configuration, and instantiate it in our beforeEach method.

describe('ComponentUnderTestComponent', () => {
  let testHostComponent: TestHostComponent;
  let testHostFixture: ComponentFixture<TestHostComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ComponentUnderTestComponent, TestHostComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    testHostFixture = TestBed.createComponent(TestHostComponent);
    testHostComponent = testHostFixture.componentInstance;
    testHostFixture.detectChanges();
  });

  it('should show TEST INPUT', () => {
    expect(testHostFixture.nativeElement.querySelector('div').innerText).toEqual('TEST INPUT');
  });

  @Component({
    selector: `host-component`,
    template: `<component-under-test input="test input"></component-under-test>`
  })
  class TestHostComponent {
  }
});

What results are green tests and the input is upcased at the beginning.

However, can we really be sure that the input gets upcased and that our component not just always displays “INPUT TEXT”? Let’s write another test that upcases “different test input”.

What we could do to achieve this is define another TestHostComponent which binds another input but we can do better than that!

  it('should show TEST INPUT', () => {
    testHostComponent.setInput('test input');
    testHostFixture.detectChanges();
    expect(testHostFixture.nativeElement.querySelector('div').innerText).toEqual('TEST INPUT');
  });

  it('should show DIFFERENT TEST INPUT', () => {
    testHostComponent.setInput('different test input');
    testHostFixture.detectChanges();
    expect(testHostFixture.nativeElement.querySelector('div').innerText).toEqual('DIFFERENT TEST INPUT');
  });
  @Component({
    selector: `host-component`,
    template: `<component-under-test [input]="input"></component-under-test>`
  })
  class TestHostComponent {
    private input: string;

    setInput(newInput: string) {
      this.input = newInput;
    }
  }

setInput() sets the input in our host component. Assigning the input in our test before we let Angular detect the changes allows both our tests to pass…

Now, imagine we have to bind not only one but multiple inputs to our component. Do we now need to write a setter method for each input?

Luckily, the answer is no!

  it('should show DIFFERENT TEST INPUT', () => {
    testHostComponent.componentUnderTestComponent.input = 'different test input';
    testHostFixture.detectChanges();
    expect(testHostFixture.nativeElement.querySelector('div').innerText).toEqual('DIFFERENT TEST INPUT');
  });
  @Component({
    selector: `host-component`,
    template: `<component-under-test></component-under-test>`
  })
  class TestHostComponent {
    @ViewChild(ComponentUnderTestComponent)
    public componentUnderTestComponent: ComponentUnderTestComponent;
  }

Instead of having a setter at all, we can also get a reference to our component from within the host component and pass it into our test. There we have full control over our component and can modify any field we want.

Summary

  • To test components that bind an input via the @Input() decorator, we can create a host component in our test to wrap our test component.
  • For multiple test inputs, we can add a setter to our host component.
  • For more that one input binding and even more control over our component under test, we can grab it from within the host component with @ViewChild and pass it into our test directly.

Thank you for reading!

#angular #javascript #front end development

What is GEEK

Buddha Community

Using @Input() to Testing Components in Angular
Marcelle  Smith

Marcelle Smith

1591081592

Create a Component Harness For Your Tests With Angular CDK

Learn how to create and consume a custom component harness using Angular CDK. With a step-by-step case study, we run it in unit tests and end-to-end tests.

Updated for Angular CDK and Angular Material version 9.2.

A component harness is a testing API around an Angular directive or component. Component harnesses can be shared between unit tests, integration tests, and end-to-end tests. They result in less brittle tests as implementation details are hidden from test suites.

#angular #angular-cdk #component-harnesses #testing #angular-material

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Roberta  Ward

Roberta Ward

1595344320

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill.

Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.

Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!

And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!

If you are still not aware of it, don’t worry as Georgia Byng has well said,

“No time is better than the present”

– Georgia Byng, a British children’s writer, illustrator, actress and film producer.

No matter if you are a developer (be it front-end or back-end) or a data scientisttester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.

From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.

How to upgrade your skills?

Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.

These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.

Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).

xlr8rs make your development real fast by just adding your core business logic to the template.

If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂

Confused with which technology to start with?

To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.

Since we believe:

“There’s always a scope of improvement“

If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.

#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade

Roberta  Ward

Roberta Ward

1593144120

Basic Introduction to Unit Testing in Angular

What is Unit Testing?

Unit testing is testing a unit in an isolated environment. A unit can be a class, component, service, directive module, etc. which can be logically separated from the software. Any unit in an app is not isolated, it’s quite normal that it will be depending on the other units in an application for resources like data or methods.

So if we do an integrated test of the application and it fails then it’s hard to identify where exactly the code is breaking. So the purpose of unit testing is to test each unit individually and see if it’s working fine.

Benefits of Unit Testing

Reveal design mistakes

You may encounter difficulty while writing tests which might reveal that the design is not correct and you may be violating some important coding principles. Or after running the test it shows unexpected behavior.

Add new features without breaking anything

If you add any new feature into existing code and after running test passes then you can be confident it won’t break the application.

Simplifies debugging process

As discussed earlier it makes it easy to exactly identify where the code is breaking.

Tests make developers more confident about their work

So, we will understand unit testing in angular by looking at some basic simple examples and then getting to know why and how we have done.

#angular #angular #angular9 #jasmine #karma #testing #unit tesing in angular #unit testing

Marcelle  Smith

Marcelle Smith

1595250300

Testing Angular Routing Components with the RouterTestingModule

This article teaches us about shallow and integrated routing component tests. The RouterTestingModule is useful for integrated routing component tests. To learn what the RouterTestingModule does, we discuss the Location service and its dependencies.

One of the use cases for Angular’s RouterTestingModule is to test Angular routing components.

An Angular routing component is a component that is used to trigger application navigation. It could be a navigation menu component, a component with one or more RouterLink directives, or it could be a component that calls Router#navigate or Router#navigatebyUrl.

In this article, we’re going to explore what the RouterTestingModule does and how we can use it to test routing components.

Figure 1. The show hero detail use case.

As a case study, we write routing component tests for the DashboardComponent from the Tour of Heroes tutorial on Angular.io. This routing is part of the show hero detail use case as shown in Figure 1:

  1. The user clicks a top hero in the dashboard.
  2. The application navigates to the hero detail.

THIS AD MAKES CONTENT FREE. HIDE

**Angular’s ****RouterTestingModule**#

To learn what Angular’s RouterTestingModule does, we first have to learn about Angular’s Location service, its dependencies and how it’s related to the Angular router.

What does Angular’s **Location** service do?#

Figure 2 illustrates the flow of dependencies from the Router service through the Location service and all of its dependencies all the way down to the browser APIs.

Figure 2. The dependency hierarchy from the Router service through the Location service and to the browser APIs.

The dark box names the the dependency injection symbol. The inner light box names the dependency that is provided when using the BrowserModule and RouterModule Angular modules.

The Router service subscribes to the @angular/common package’s PopStateEvents which have the interface listed in Listing 1. It uses the Location service to be notified of these events.

interface PopStateEvent {
  pop?: boolean;
  state?: any;
  type?: string;
  url?: string;
}
<>

Listing 1. The PopStateEvent interface from @angular/common.

PopStateEvent wraps a native popstate or hashchange browser event and enriches it with metadata that the Angular router uses to identify which route to activate.

When Router#navigate or Router#navigateByUrl is called or a RouterLink directive is activated, the router figures out which route to activate and uses the Location service to replace the browser’s history state stack.

From Figure 2 we can tell that the Location service itself delegates work to other Angular services. The concrete LocationStrategy services are used to decide between path- or hash-based navigation. The concrete PlatformLocation interacts with browser APIs to query parts of the URL through the Location API or listen for history stack state changes or hash changes through the History API.

#angular #testing #angular-router #routertestingmodule #angular