- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我为我拥有的一个组件创建了一堆单元测试。它最初是失败的,因为我得到了上述错误,所以我取出了 event.defaultPrevented 东西,但实际上并不知道它在做什么。
好吧,这修复了我的错误,但显然对 UI 行为产生了非常糟糕的副作用,所以我不得不将这些东西放回我的代码中。
所以,现在我要回去修复我的单元测试了。我如何能够模拟/注入(inject)事件内容到我的单元测试中?
只有 Angular CLI stub 的默认“应该创建”测试失败了,代码如下:
let component: MemberAddComponent;
let fixture: ComponentFixture<MemberAddComponent>;
let contractsService: ContractsService;
let notesService: NotesService;
let saveButton: any;
beforeEach(async(() => {
let router = { navigate: jasmine.createSpy('navigate') };
TestBed.configureTestingModule({
imports: [
HttpModule,
FormsModule,
ReactiveFormsModule,
RouterTestingModule
],
declarations: [
MemberAddComponent,
// lots more here
],
providers: [
AppDataService,
ErrorService,
{
provide: ContractsService,
useClass: MockContractsService
},
{
provide: NotesService,
useClass: MockNotesService
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MemberAddComponent);
component = fixture.componentInstance;
contractsService = fixture.debugElement.injector.get(ContractsService);
saveButton = fixture.nativeElement.querySelector('#saveButton');
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
这里是 ngOnInit 函数,它应该是该测试唯一运行的函数:
ngOnInit() {
this.log('ngOnInit', 'ngOnInit...');
this.routeSubscription = this.route.params.subscribe(params => {
this.memberId = params['id'] || null;
this.effectiveDate = params['from'] || null;
this.cancelDate = params['to'] || null;
this.group = params['group'] || null;
this.subgroup = params['subgroup'] || null;
});
this.contractRequest = new models.AddContractRequestUI();
this.dataservice.effectiveDateOfChange = this.dataservice.getCurrentDateMountainTimezone();
this.dataservice.todaysDateString = this.dataservice.effectiveDateOfChange;
if (this.contractRequest.subscriber.class.length === 0) {
this.contractRequest.subscriber.class.push(new models.AddContractRequestSubscriberClass(this.dataservice.effectiveDateOfChange));
}
this.loadContractDetails();
this.dependent.originalEffectiveDt = this.dataservice.effectiveDateOfChange;
this.memberComplete = false;
this.transactionStartTime = new Date();
}
编辑:注意在被测试的代码中的任何地方都没有 event.preventDefault
或 event.defaultPrevented
。它仅存在于该组件上发布/提交过程的 onSubmit
函数中。但它仍然使单元测试失败。
Edit2:这是 html 页面,以及 onSave() 函数
HTML:
<div class="container">
<div *ngIf="!waiting" class="row mb-20">
<div class="col-xs-12">
<a class="link-icon" (click)="onClickBack()">
<span class="icon-wmkCaretLeft"></span>
<span class="link-text text-uppercase text-condensed">Back</span>
</a>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<form *ngIf="(!loadError)" novalidate (ngSubmit)="onSave()">
<template [ngIf]="groupComplete">
<wm-groupinfo-view [groupName]="contractRequest.groupName" [groupId]="contractRequest.groupIdentifier" [subgroupId]="contractRequest.subgroupIdentifier"></wm-groupinfo-view>
</template>
<template [ngIf]="groupComplete && !effectiveDateComplete">
<member-add-effective-date [componentTitle]="enterEffectiveDateTitle" [effectiveDateString]="dataservice.effectiveDateOfChange" (complete)="onEffectiveDateComplete($event)"></member-add-effective-date>
</template>
<template [ngIf]="groupComplete && effectiveDateComplete">
<h3 class="text-uppercase">Effective Date</h3>
<p><span class="field-label">Effective Date of Change: </span>{{ dataservice.effectiveDateOfChange | wmFixDateFormat }}</p>
<div class="buttons">
<button class="btn btn-primary" (click)="onClickEditEffectiveDate()">
<i class="glyphicon glyphicon-edit"></i>
Edit Effective Date
</button>
</div>
</template>
<template [ngIf]="effectiveDateComplete">
<member-add-subscriber-info [member]="contractRequest.member[0]" [subscriberId]="memberId" (complete)="onSubscriberInfoComplete($event)"></member-add-subscriber-info>
</template>
<template [ngIf]="subscriberDemoComplete">
<template [ngIf]="!homeAddressInfoComplete">
<member-add-subscriber-address [address]="homeAddressObject" (complete)="onAddressInfoComplete($event)"></member-add-subscriber-address>
</template>
<template [ngIf]="homeAddressInfoComplete">
<h3 class="text-uppercase">Subscriber Home Address Information</h3>
<p *ngIf="dataservice.selectedContract.address[0].type === 'Primary'"><strong>Address Type: </strong>HOME</p>
<p *ngIf="dataservice.selectedContract.address[0].type !== 'Primary'"><strong>Address Type: </strong>MAILING</p>
<p><strong>Address Line 1: </strong>{{dataservice.selectedContract.address[0].addressLine1}}</p>
<p><strong>Address Line 2: </strong>{{dataservice.selectedContract.address[0].addressLine2}}</p>
<p><strong>City: </strong>{{dataservice.selectedContract.address[0].city}}</p>
<p><strong>State: </strong>{{dataservice.selectedContract.address[0].state}}</p>
<p><strong>Zip Code: </strong>{{getZipString(0)}}</p>
<p><strong>County: </strong>{{dataservice.selectedContract.address[0].county?.description}}</p>
<p><strong>Email: </strong>{{dataservice.selectedContract.address[0].email}}</p>
<p><strong>Phone Number: </strong>{{ dataservice.selectedContract.phoneNumber | wmPhonePipe }}</p>
<div class="buttons">
<button class="btn btn-primary" (click)="onClickEditAddressInfo()">
<i class="glyphicon glyphicon-edit"></i>
Edit Subscriber Home Address
</button>
</div>
<template [ngIf]="!showMailingAddress">
<div class="buttons">
<button class="btn btn-primary" (click)="onClickAddMailingAddressInfo()">
<i class="glyphicon glyphicon-add"></i>
Add Subscriber Mailing Address
</button>
</div>
</template>
<template [ngIf]="showMailingAddress">
<template [ngIf]="!mailingAddressInfoComplete">
<member-add-subscriber-address [address]="mailingAddressObject" (complete)="onMailingAddressInfoComplete($event)" (delete)="onClickDeleteMailingAddressInfo($event)"></member-add-subscriber-address>
</template>
<template [ngIf]="mailingAddressInfoComplete">
<h3 class="text-uppercase">Subscriber Mailing Address Information</h3>
<p *ngIf="dataservice.selectedContract.address[1].type === 'Primary'"><strong>Address Type: </strong>HOME</p>
<p *ngIf="dataservice.selectedContract.address[1].type !== 'Primary'"><strong>Address Type: </strong>MAILING</p>
<p><strong>Address Line 1: </strong>{{dataservice.selectedContract.address[1].addressLine1}}</p>
<p><strong>Address Line 2: </strong>{{dataservice.selectedContract.address[1].addressLine2}}</p>
<p><strong>City: </strong>{{dataservice.selectedContract.address[1].city}}</p>
<p><strong>State: </strong>{{dataservice.selectedContract.address[1].state}}</p>
<p><strong>Zip Code: </strong>{{dataservice.selectedContract.address[1].zip}}</p>
<p><strong>County: </strong>{{dataservice.selectedContract.address[1].county?.description}}</p>
<div class="buttons">
<button class="btn btn-primary" (click)="onClickEditMailingAddressInfo()">
<i class="glyphicon glyphicon-edit"></i>
Edit Subscriber Mailing Address
</button>
<button class="btn btn-primary" (click)="onClickDeleteMailingAddressInfo()">
<i class="glyphicon glyphicon-edit"></i>
Delete Subscriber Mailing Address
</button>
</div>
</template>
</template>
</template>
</template>
<ng-container *ngIf="subscriberDemoComplete && homeAddressInfoComplete && (!showMailingAddress || mailingAddressInfoComplete)">
<member-add-dependent *ngIf="addingDependents" [member]="dependent" [editing]="isEditingDependent" (complete)="onDependentComplete($event)"></member-add-dependent>
<div *ngIf="dependentComplete">
<h3 class="text-uppercase">Dependent/Member Information</h3>
<p><strong>Relationship: </strong>{{ dataservice.getRelationshipString(dependent.relationship) }}</p>
<p><strong>First Name: </strong>{{dependent.firstName}}</p>
<p><strong>Middle Initial: </strong>{{dependent.middleInitial}}</p>
<p><strong>Last Name: </strong>{{dependent.lastName}}</p>
<p><strong>Title: </strong>{{dependent.title}}</p>
<p><strong>Date of Birth: </strong>{{ dependent.birthDt | wmFixDateFormat }}</p>
<p><strong>Social Security Number: </strong>{{dependent.ssn}}</p>
<p><strong>Gender: </strong>{{dependent.sex}}</p>
<p><strong>Marital Status: </strong>{{dependent.maritalStatus}}</p>
<p><strong>Original Effective Date: </strong>{{dependent.originalEffectiveDt | wmFixDateFormat}}</p>
<div class="buttons">
<button class="btn btn-primary" (click)="onClickEditDependentDemo(dependent)">
<i class="glyphicon glyphicon-edit"></i>
Edit Dependent Information
</button>
</div>
</div>
</ng-container>
<ng-container *ngIf="showProducts && dependentComplete">
<member-add-products [members]="contractRequest.member" [addingMember]="true" (complete)="onProductsComplete($event)"></member-add-products>
</ng-container>
<div>
<wm-error-list [errors]="errorList" (clickError)="focusField($event)" (addError)="errorAdded($event)"></wm-error-list>
</div>
<div *ngIf="(!waiting)" class="buttons pb-10">
<div *ngIf="canSave()">
<button id="saveButton" class="btn btn-primary pull-right" type="submit">Add Member</button>
</div>
<div *ngIf="!canSave()">
<button [disabled]="true" class="btn btn-primary pull-right">Add Member</button>
</div>
<button class="btn btn-secondary pull-right" type="button" (click)="onClickCancel()">Cancel</button>
</div>
<div *ngIf="(waiting)">
<wm-spinner></wm-spinner>
</div>
</form>
<div *ngIf="(loadError)">
<h3>{{errorMessage}}</h3>
</div>
</div>
</div>
</div>
保存():
onSave() {
if (event.defaultPrevented || this.waiting) {
return;
}
this.clearErrors();
this.checkErrors();
if (this.hasErrors() || (!this.unitTesting && !confirm("You are about to add this member. Are you sure you want to continue?"))) {
return;
}
this.waiting = true;
this.saveUpdatedSubscriberInformation();
var addMemberObject = this.buildAddMemberObject();
this.contractsService.addMember(addMemberObject)
.subscribe(response => {
this.parseAddMemberResponse(response, addMemberObject, true);
//only save the note on success of adding member
this.saveNote();
}, error => {
this.parseAddMemberResponse(error, addMemberObject, false);
});
}
最佳答案
如果你想阻止你的事件,你必须将事件添加到你的 onSave 函数中,所以替换
<form *ngIf="(!loadError)" novalidate (ngSubmit)="onSave()">
与
<form #myForm="ngForm" *ngIf="(!loadError)" novalidate (ngSubmit)="onSave(myForm, $event)">
并将参数添加到OnSave函数
public onSave(myForm: any, event: Event) {
event.preventDefault(); // or event.defaultPrevented to check
.... rest of your code
}
关于Angular 2单元测试报错Unable to get property 'preventDefault' of undefined or null reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45820968/
我正在努力学习本教程 https://github.com/cf-platform-eng/spring-boot-cities/tree/master/cities-service在 Cloud F
0){ echo "Username or email already exists."; }else{ $query = mysql_que
我想在Linux上编译ARToolKit源码,下载源码,按照ARToolKit文档,配置GLUT , OpenGL, libjpeg 等库。 转到 ARToolKit 目录并键入 ./Configer
你好,我在这个程序中遇到错误,wcout 不是 `std' 的成员。如您所见,我也使用了 iostream,但没有用。我有 Dev-C++ 4.9.9.2,我的操作系统是 XP SP3我需要你的帮助。
我尝试对一个网站进行多次投票,但我得到: panic: runtime error: invalid memory address or nil pointer dereference [signal
当我将“ using namespace std; int main(){ string s[30]; int n = 20; for(int i = 0; i using
我设置了 EMAIL_URL process.env.MAIL_URL="smtp://xx%40gmail.com:yyy@smtp.gmail.com:465" 这个工作找到了 Email.sen
我有如下文件夹结构 . ├── docker-compose.yml └── web-app ├── create_tomcat_admin.sh ├── Dockerfile
这是我在 php 中的查询代码: $query3 = mysql_query("SELECT * FROM area_of_work") or die('Invalid query:'. mysql_
我正在尝试将 therubyracer/therubyracer-heroku 安装到我的应用程序,因为它在 heroku 服务器中不起作用,因为我没有 javascript 运行时环境。 当我尝试安
我正在开发一个非常简单的 React 应用程序。它有一个组件,在这个组件中,我试图在单击链接时设置状态。但出于某种原因,setState 甚至没有得到认可。它带有下划线,表示未解析的函数或方法 set
我有三个来源:代码处理.h typedef enum {typeBool, typeVarDeclaration, typeFuncDeclaration } nodeEnum; typedef st
我正在尝试从我的 Android 手机向 raspi 发送连续的命令。我使用了此链接中的代码,但出现错误。 链接:https://stackoverflow.com/questions/2347143
我正在尝试从数据库中加载数据并将其放入不同的 View 中。 log cat 返回错误,它找不到“_id”列。 有人可以帮我解决这个问题吗? SqlHelper代码: public class Fib
我的alertview给出了这个问题..它与sqlite无关..它给出了一些信息.. 我该如何解决这个问题? UIAlertView *infoShow = [[UIAlertView alloc]
这个问题在这里已经有了答案: launch activities from different package (5 个答案) 关闭 10 年前。 最近我一直在开发一个新的应用程序,我正在尝试使用
这是我的代码: #include #include typedef struct test { int *a; char *s; }TEST; int main (void) {
所以我定义了一个函数,如果它是由它的 lonesome 实现的,那么它非常适合对线性数组进行合并排序,但是如果我把它放到一个类中,它就会出错。我认为这是一个很好的例子,说明我不太了解类(class)的
我是 IOS 新手。我有一个示例项目,并试图在此基础上学习 Obj-C。 现在我正处于学习如何使用 UIAlertController 的阶段。我有这样的代码: if (loanAmount == 0
当我尝试使用 wincachegrind 并获取 cachegrind 文件时,它返回 Cannot find call target. cachegrind.out line number:68 有
我是一名优秀的程序员,十分优秀!