在单元测试中使用模拟Dart Angular替换提供程序

时间:2017-03-19 13:20:31

标签: unit-testing angular mocking dart mockito

如何在Angular Dart单元测试中将提供程序QuizService替换为QuickServiceMock

我尝试使用addProviders方法,但未将QuizService替换为QuizkServiceMock

似乎MultipleChoiceQuizComponent仍在使用原始课程QuizkService,而不是我想要的QuizServiceMock

import 'dart:html';
import 'package:angular2/angular2.dart';
import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';

import '...quiz_service.dart';
import '...multiple_choice_quiz_component.dart';
import '...multiple_choice_quiz.dart';

class MockQuizService extends Mock implements QuizService {}

@AngularEntrypoint()
void main()
{
    group('$MultipleChoiceQuizComponent', () {
        MockQuizService quizServiceMock;
        setUp(() async {
            quizServiceMock = new MockQuizService();
            List<String> mockChoiceList = [
                "incorrect1",
                "incorrect2",
                "correct answer",
                "incorrect3"
            ];
            when(quizServiceMock.getQuiz())
                .thenReturn(
                    new MultipleChoiceQuiz(
                        mockChoiceList,
                        "correct answer",
                        'test question description'
                )
            );
        });

        test('should add "incorrect" css class to incorrect answer', () async {
            NgTestBed bed = new NgTestBed<MultipleChoiceQuizComponent>().addProviders([
                provide(QuizService, useValue: quizServiceMock)
            ]);
            NgTestFixture fixture = await bed.create();
            Element answer = fixture.rootElement.querySelector('.quiz-choice:nth-child(2)');
            answer.dispatchEvent(new MouseEvent('click'));
            bool hasClass = answer.classes.contains('incorrect');
            expect(hasClass, true);
        });
    });

}

multiple_choice_quiz_component.dart:

import 'package:angular2/core.dart';
import 'package:angular2/common.dart';
import 'package:angular2_components/angular2_components.dart';

import '.../quiz/quiz.dart';
import '.../service/quiz_service.dart';

@Component
(
    selector: 'multiple-choice-quiz-component',
    directives: const [materialDirectives, NgFor],
    providers: const [materialProviders, QuizService],
    templateUrl: 'multiple_choice_quiz_component.html',
    styleUrls: const['/app_component.css', 'quiz.css']
)

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);
    }
}

我错过了什么?

1 个答案:

答案 0 :(得分:0)

您无法覆盖窗口小部件的providers:注释中的@Component

您可以做的是将树中的绑定移动到更高位置,以便父级(或应用程序引导程序)提供绑定。