如何使用Jasmine将依赖性注入到Angular单元测试中?

问题描述 投票:0回答:1

我第一次尝试在Angular中实现单元测试,我正在使用Jasmine。我来自Java \ Spring,使用Spring框架会自动将所有依赖项注入测试中,但我不知道如何使用带有[[Jasmine的Angular Unit Test。我试图更好地解释我要做的事情。

1)我有这个

PeopleListComponent

组件类:import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; import { EventService } from '../event.service'; import interactionPlugin, { Draggable } from '@fullcalendar/interaction'; interface WorkShiftTypes { name: string; value: string; } @Component({ selector: 'app-people-list', templateUrl: './people-list.component.html', styleUrls: ['./people-list.component.css'] }) export class PeopleListComponent implements OnInit { people: any[]; //cities: City[]; workShiftTypes: WorkShiftTypes[]; selectedShift: WorkShiftTypes; @ViewChild('draggable_people') draggablePeopleExternalElement: ElementRef; constructor(private eventService: EventService) { } ngOnInit(): void { this.eventService.getPeople().then(people => {this.people = people;}); this.selectedShift = {name: 'Mattina', value: 'Mattina'}; this.workShiftTypes = [ {name: 'Mattina', value: 'Mattina'}, {name: 'Pomeriggio', value: 'Pomeriggio'}, {name: 'Notte', value: 'Notte'}, {name: 'Custom', value: 'Custom'} ]; } ngAfterViewInit() { console.log("PEOPLE LIST ngAfterViewInit() START !!!") var self = this new Draggable(this.draggablePeopleExternalElement.nativeElement, { itemSelector: '.fc-event', eventData: function(eventEl) { console.log("DRAG !!!"); //console.log("SELECTED SHIFT: " + self.selectedShift.value); return { title: eventEl.innerText, startTime: "17:00", duration: { hours: 8 } }; } }); } createEventObject() { return 1; } }
如您所见,该组件包含此非常简单的方法

createEventObject()

createEventObject(){返回1;}

目前仅返回值1(我想尽可能简单地尝试单元测试,然后实现实际用例)。

确定,所以我创建了这个

people-list-spec.ts

文件,其中包含前一种方法的单元测试:
import { PeopleListComponent } from "./people-list.component" import { EventService } from '../event.service'; describe('people-list', () => { let eventService = new EventService(); let component = new PeopleListComponent(eventService); it('createEventObject() return 1', () => { }) })
确定,所以我要做的就是获取一个

PeopleListComponent

实例,在其上调用createEventObject()并检查返回的值是否为1以断言单元测试成功。
并且这里我遇到以下问题:

PeopleListComponent

构造函数使用EventService paramether。好的...我可以构建它并通过它,但是EventService构造函数采用一个[[HttpClient
参数。所有这些依赖项注入都由我的项目中的Angular自动处理,我怀疑手动创建不是正确的选择(很多代码重复,而且Angular应该处理HttpClient类)。该问题的解决方案是什么?使用Spring框架还可以为单元测试项目处理依赖项注入,我认为(并希望)在Angular \ Jasmine中是相同的,但是我到底要做什么?

我第一次尝试在Angular中执行单元测试,我正在使用Jasmine。我来自Java \ Spring,并使用Spring框架自动将所有依赖项注入测试中,但是我...

angular typescript unit-testing jasmine angular-unit-test
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.