单元测试angular4组件 - 测试组件函数并使用组件属性时出现错误

时间:2018-04-12 05:53:59

标签: angular jasmine angular-components

以下是我的组件的HTML:

列表comments.component.html

<div class="container">

    <div class="row listCommentsContainer">
      <h2>Best Of Books</h2>
        <div class="col-lg-8 col-sm-8" *ngFor="let commentData of commentsData; let i = index">
          <ol style="list-style: none;">
          <li class="listComments">

            <div  style="display: block">
            <div style="display:inline-block;">
              <a class="avatar">

                <img style="" src="{{commentData.profile_image}}">
              </a>
            </div>
            <a class="commentPostByUserName">
              <span class="commentPostByUserName" style="">{{commentData.first_name}}</span>
            </a>
              <div class="commentTime">{{commentData.time_stamp}}</div>
            </div>
            <div class="commentTextDisplay">{{commentData.object}}</div>

            <br>

            <!-- Click Reply -->
            <div class="addReplyContainer" #commentData.id>
              <a  class="addReplyLink"  (click)="showReplyTextArea($event, commentData.id)">Reply</a>
            </div>

            <!-- Add Reply -->
            <div [attr.commentId]="commentData.id" class="addReplyContainer replyTextAreaContainer" style="display: none" >
              <textarea (keyup)="keyUpCommentTextarea($event, reply, commentData.id)" [(ngModel)]="reply" style="width:100%"
                        class="replyText commentText addReplyTextarea form-control"></textarea>
              <button [attr.commentId]="commentData.id" disabled class="btn btn-success addCommentBtn" (click)="addReply($event, commentData.target_id)">Add</button>
            </div>
            <!-- -----Add Reply end------ -->

            <!-- List Replies -->
            <div class="replies col-lg-8 col-sm-8" *ngFor="let reply of commentData.comment">
              <ol style="list-style: none;">
                <li class="listComments listReplies">

                  <div  style="display: block">
                    <div style="display:inline-block;">
                      <a class="avatar">

                        <img style="" src="{{reply.profile_image}}">
                      </a>
                    </div>
                    <a class="commentPostByUserName">
                      <span class="commentPostByUserName" style="">{{reply.first_name}}</span>
                    </a>

                  </div>
                  <div class="commentTextDisplay replyTextDisplay">{{reply.object}}</div>
                </li>
              </ol>
            </div>
            <!-- -------list reply end-------- -->

          </li>
          </ol>
        </div>

    </div>

    <!-- Add Comment-->
    <div class="row">
      <div  class="addCommentContainer col-lg-6 col-sm-12">

          <textarea (keyup)="keyUpCommentTextarea($event, comment)"
                    [(ngModel)]="comment" class="commentText form-control"
                    placeholder="Add Comment">
          </textarea>
        <button  disabled (click)="addComment($event)" class="btn addCommentBtn btn-success">Add</button>

      </div>
    </div>
  <!-- Add Comment end-->
</div>

这是我的spec文件:

列表comments.component.spec.ts:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ListCommentsComponent } from './list-comments.component';
import {DebugElement} from "@angular/core";
import 'reflect-metadata';
import { Component } from  "@angular/core";
import {By} from "@angular/platform-browser";
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
// require('zone.js');
// let chai = require('chai') ,
// spies = require('chai-spies');
// chai.use(spies);


describe('ListCommentsComponent', () => {
  let component: ListCommentsComponent;
  let fixture: ComponentFixture<ListCommentsComponent>;
  let debugElement:DebugElement;
  let htmlElement:HTMLElement;



  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, HttpClientModule],
      declarations: [ ListCommentsComponent ],
     // providers:[HttpClientModule, HttpClient]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ListCommentsComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();


  });



  fit('should be disabled', () => {

    debugElement = fixture.debugElement.query(By.css('button.addCommentBtn'));
    htmlElement =debugElement.nativeElement;
    expect(htmlElement.getAttribute('disabled')).toEqual('disabled');
  });

});

在上面的测试中,我只想检查“如果我的按钮已禁用属性”。

请告诉我如果这不是在页面加载时检查按钮的已禁用属性的正确方法。

提前致谢。

*修改

搜索了几个小时后,我发现我可以使用jQuery解决访问debugElement属性的问题。 因此,我使用$而不是使用debugElement,它完全正常。

我已将我的spec文件修改为:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ListCommentsComponent } from './list-comments.component';
import {DebugElement} from "@angular/core";
import 'reflect-metadata';
import { Component } from  "@angular/core";
import {By} from "@angular/platform-browser";
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
 import * as $ from 'jquery';
// require('zone.js');
// let chai = require('chai') ,
// spies = require('chai-spies');
// chai.use(spies);


describe('ListCommentsComponent', () => {
  let component: ListCommentsComponent;
  let fixture: ComponentFixture<ListCommentsComponent>;
  let debugElement:DebugElement;
  let htmlElement:HTMLElement;




  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, HttpClientModule],
      declarations: [ ListCommentsComponent ],
     // providers:[HttpClientModule, HttpClient]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ListCommentsComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();


  });



  fit('should not be disabled when we add message', () => {

    component.keyUpCommentTextarea("hello", null);


      let addCommentBtn = $('button.addCommentBtn').attr('disabled');

    debugElement = fixture.debugElement.query(By.css('button.addCommentBtn'));

    expect(addCommentBtn).toEqual(undefined);
  });


  fit('should  be disabled when we do not add message', () => {

    component.keyUpCommentTextarea("", null);


    let addCommentBtn = $('button.addCommentBtn').attr('disabled');



    expect(addCommentBtn).toEqual('disabled');
  });


  fit('should match array',  () => {

    let commentsJson = {
      root_id:"1",
      target_id: 1,
      text: "hi",
      comment_posted_by:"Jack",
      comment_posted_by_image:"/../../assets/images/no-user.png",
      profile_image:"/../../assets/images/no-user.png",
      first_name : "john"
    };

    component.addComment();

    expect(commentsJson).toEqual(component.commentObj);

  });



  it('should be string',  () => {

    component.addComment();
    expect(component.comment).toBe('string');

  });


});

在我的上一次测试中,我调用了功能 addComment ,它涉及 this.comment this.commentObj 代码到达访问this.comment的行时 list-comment组件的属性我得

  

TypeError:无法读取属性&#39; trim&#39;未定义的

我的代码出了什么问题?

0 个答案:

没有答案