Angular2Noob
Angular2Noob

Reputation: 11

How to write Jasmine unit tests in Angular2 for an element with data binding and pipes

I have never written unit tests in jasmine to test an HTML element and I'm hoping to get an answer as well as some resources on the topic.

Here's the code:

<div class="ui-g-4 patientName">
    <h1><b [innerText]="header.patient.name || na"></b>,</h1>
    <div class="patientInfo">
        <h3><b [innerText]="header.patient.sex || na"></b></h3>
        <h3><b [innerText]="(header.patient.dateOfBirth | date) || na"></b></h3>
    </div>
</div>

As you can see I have a 'h1' and 2 'h3'. On the patient.dateOfBirth I also use a pipe for the filter of date.

As I said before, I've never written tests for this kind of thing and have no idea where to start. If you know of resources, links or examples feel free to post so I can read more about it. If you feel like writing the 'describe' and the 'it(should...' with descriptions I'd appreciate it as well.

Thanks

Upvotes: 1

Views: 3739

Answers (1)

Yakov Fain
Yakov Fain

Reputation: 12376

In your unit spec you need to create component programmatically, assign the values to the properties of your patient object, and initiate the detection change so the binding will kick in.

TestBed.createComponent() returns the object ComponentFixture that has references to both the component and the native HTML element.

Via the fixture you access component properties and find specific HTML elements within the component template.

    it('should display patient data ', () => {
     

     let fixture = TestBed.createComponent(PatientComponent);
 
   
        
     let element = fixture.nativeElement;         // DOM element
          
     let component = fixture.componentInstance;   // Angular component
        


  component.header.patient = {name: "Mary", ...}; // assign values to the patient obj

  fixture.detectChanges(); // trigger change detection to update the DOM element
    
    
      

  expect(element.querySelector('h1').innerHTML).toBe('Mary');
     
  ...
  });

After invoking detectChanges() the bindings will be applied and pipes will do their transformations. Read the docs about component testing here: https://angular.io/docs/ts/latest/guide/testing.html

Upvotes: 4

Related Questions