2017-03-18 114 views
2

我使用angular_test.dart來測試我的組件。我想測試點擊某個特定的<li>會將其標記爲選中狀態。如何在角度飛鏢測試中觸發組件事件?

multiple_choice_quiz_component.html

<div> 
    <div class="contain-center"> 
    <h1>{{quiz.getDescription}}</h1> 
    </div> 
    <div class="contain-center"> 
     <ul> 
      <li *ngFor="let answer of quiz.getChoiceList" 
       (click)="onSelect(answer)" 
       [class.selected]="answer == selectedAnswer" 
       [class.correct]="correctAnswer && answer == selectedAnswer" 
       [class.incorrect]="!correctAnswer && answer == selectedAnswer" 
      > 
       {{answer}} 
      </li> 
     </ul> 
    </div> 
</div> 

multiple_choice_quiz_component.dart

class MultipleChoiceQuizComponent 
{ 
    String selectedAnswer; 
    String description; 
    bool correctAnswer = false; 
    Quiz quiz; 

    MultipleChoiceQuizComponent(QuizService quizService) 
    { 
     this.quiz = quizService.getQuiz(); 
    } 

    void onSelect(String answer) 
    { 
     selectedAnswer = answer; 
     this.correctAnswer = this.quiz.isAnswer(answer); 
    } 
} 

test.dart

... 
import 'package:angular_test/angular_test.dart'; 
.... 
group('My Tests',() { 
    test('should change li element to selected',() async { 
    var bed = new NgTestBed<MultipleChoiceQuizComponent>(); 
    var fixture = await bed.create(); 
    await fixture.update((MultipleChoiceQuizComponent Component) { 
    }); 
});}); 

在我的測試中,如何觸發點擊讓我們說第二個<li>並評估它具有選定的屬性?我該如何嘲笑測驗服務並將其注入構造函數?

回答

2

我以爲我不想弄明白,但我做到了。

使用debug html test file幫助了很多。在控制檯上,我可以設置斷點。使用控制檯,我可以瀏覽這些對象的方法來找出我需要調用的內容。

NgTestBed bed = new NgTestBed<MultipleChoiceQuizComponent>(); 
    NgTestFixture fixture = await bed.create(); 
    Element incorrectAnswer = fixture.rootElement.querySelector('.quiz-choice:nth-child(2)'); 
    incorrectAnswer.dispatchEvent(new MouseEvent('click')); 
    bool hasClass = incorrectAnswer.classes.contains('incorrect'); 
    expect(true, hasClass);