我有一个按钮组件,它接受承诺并禁用按钮,直到承诺解决为止,并且我想为此功能编写单元测试。
我的按钮组件有一个承诺的输入
/**
* A single promise that triggers the busy state until it resolves
*/
@Input()
public promise: Promise<any>;
Run Code Online (Sandbox Code Playgroud)
在ngOnChanges内部,我听了承诺
/**
* Enable button busy state until promise resolves
*/
if (changes && changes.promise && changes.promise.currentValue) {
this.busyUntilPromiseResolves(changes.promise.currentValue);
}
Run Code Online (Sandbox Code Playgroud)
然后,我存储了一个有效的promise数组,以便可以传递多个promise
/**
* Add a promise that will keep the button in a busy state until it resolves
* @param activityProimise
*/
private busyUntilPromiseResolves(activityProimise) {
this.activityPromises.push(activityProimise);
activityProimise.then(() => {
this.activityPromises.splice(this.activityPromises.indexOf(activityProimise), 1);
});
}
Run Code Online (Sandbox Code Playgroud)
然后最后在我的模板中,如果数组中有任何promise,我将禁用按钮。
[disabled]="activityPromises.length > 0"
Run Code Online (Sandbox Code Playgroud)
unit-testing promise angular-components angular angular-unit-test
我想编写一个简单的单元测试,以检查当某些值为null或为空时按钮是否被禁用。
以下是我的规格文件:
测试规范
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import 'reflect-metadata';
import { Component,
DebugElement,
ViewChild }
from "@angular/core";
import {By} from "@angular/platform-browser";
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { ListCommentsComponent } from './list-comments.component';
import {CommentsDataService} from '../../services/comments/comments-data.service'
describe('ListCommentsComponent', () => {
let component: ListCommentsComponent;
let fixture: ComponentFixture<ListCommentsComponent>;
let debugElement:DebugElement;
let htmlElement:HTMLElement;
let addCommentBtn:DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ FormsModule, HttpClientModule],
declarations: [ ListCommentsComponent ],
providers:[{provide: CommentsDataService}],
// providers:[HttpClientModule, …Run Code Online (Sandbox Code Playgroud) 我已经构建了一个HttpInterceptor紧跟 Angular 文档中的那个。
但是,作为拦截器的一部分,我需要进行异步调用。我用代码的简化版本(但语义相同)创建了一个StackBlitz。
拦截器看起来像:
export class AuthInterceptor implements HttpInterceptor {
constructor(private session: SessionService, private config: ConfigurationService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const apiRoot = this.config.apiUrl;
if (apiRoot && req.url.startsWith(apiRoot)) {
return this.addAuth(req).pipe(switchMap(x => next.handle(x)));
} else {
return next.handle(req);
}
}
private addAuth(original: HttpRequest<any>): Observable<HttpRequest<any>> {
return from(this.session.getToken()).pipe(
map(token => {
const req = original.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return req;
})
);
}
}
Run Code Online (Sandbox Code Playgroud)
这很简单:
req.url.startsWith() …unit-testing angular-http-interceptors angular angular-unit-test
我正在尝试模拟一个文件Drop事件来测试角度指令,但我无法设法创建DragEvent.
it('should output file drop when file droped', () => {
const file = new File([''], 'dummy.txt'); // got my file right there, want to drop it on "des"
des.dispatchEvent(new DragEvent('drop', { dataTransfer: { items: [ new DataTransferItem(file)] } }));
// ...
});
Run Code Online (Sandbox Code Playgroud)
我不确定如何处理第二个参数才能将我的文件放在那里。
我的组件文件有以下代码
@ViewChild('clusterCard', { static: false }) clusterCard: ElementRef;
highLightTheClusterCard(point: PickupClusterPoint) {
if (point) {
const card: HTMLElement = _get(this.clusterCard, 'nativeElement');
const selectedPoint: PositioningPoint = this.lane.data.selectedPostioningPoint;
/* if card is available, position point of the card and the cluster is same and infowindow over the cluster is open then
highlight the card */
if (card && _isEqual(point.pointData, selectedPoint) && point.openInfoWindow) {
card.scrollIntoView();
card['style'].borderLeft = `5px solid ${this.lane.data.color || 'transparent'}`;
} else {
card['style'].borderLeft = `5px solid transparent`;
}
}
}
ngAfterViewChecked(): …Run Code Online (Sandbox Code Playgroud) 我正在 Angular 中编写 Ag-grid 的单元测试用例,其中有 Angular Grid:外部过滤器,它是切换过滤器复选框。我收到“TypeError:无法读取未定义的属性‘onFilterChanged’”
我正在测试这个方法:
toggleCheckboxMethod({ checked }): void {
isChecked = checked;
this.gridApi.onFilterChanged(); //when this method initiates it causes for test to fail
}
Run Code Online (Sandbox Code Playgroud)
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
HttpClientModule,
HttpClientTestingModule,
AgGridModule.withComponents([]),
MatDialogModule,
BrowserAnimationsModule
],
declarations: [ TestComponent ],
providers: []
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should toggle checkbox', () => {
let isChecked = false;
spyOn(component, 'toggleCheckboxMethod').and.callThrough();
component.toggleCheckboxMethod({ checked: true });
expect(component.toggleCheckboxMethod).toHaveBeenCalled();
expect(isChecked).toEqual(true); …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试模拟 Angular 单元测试的输入属性。不幸的是,我无法进一步并反复收到以下错误消息:
类型错误:无法读取未定义的属性“数据”
我的 HTML 模板如下所示
<div class="container-fluid">
<div class="row">
<div class="col-12">
<plot [data]="graph.data" [layout]="graph.layout"></plot>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我的组件是这样的:
...
export class ChartComponent implements OnInit {
@Input() currentChart: Chart;
currentLocationData: any;
public graph = {
data: [
{
type: 'bar',
x: [1, 2, 3],
y: [10, 20, 30],
}
],
layout: {
title: 'A simple chart',
},
config: {
scrollZoom: true
}
};
...
}
Run Code Online (Sandbox Code Playgroud)
我的单元测试现在看起来非常基本,但仍然抛出上述错误:
describe('ChartComponent', () => {
let component: ChartComponent;
let fixture: ComponentFixture<ChartComponent>;
beforeEach(async(() => { …Run Code Online (Sandbox Code Playgroud) unit-testing typescript karma-jasmine angular angular-unit-test
这是我的 ts 文件:
this.store.pipe(select(subscribe.getRegCategories)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => {
if (data && data.length) {
this.allRegCategories = data;
}
});
Run Code Online (Sandbox Code Playgroud)
当我去测试时出现错误:
this.store.pipe(select(subscribe.getRegCategories)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => {
TypeError: Cannot read property 'pipe' of undefined
Run Code Online (Sandbox Code Playgroud)
这里如何提供管道?解决这个问题的正确方法是什么?
这是我的测试规范文件:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Store, select } from '@ngrx/store';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientModule } from '@angular/common/http';
import { ShellViewProgMgmtComponent } from './shell-view-prog-mgmt.component';
import { ViewProgMgmtComponent } from './../../components/view-prog-mgmt/view-prog-mgmt.component';
import * as actions from './../../state/actions/setup-config.actions';
describe('ShellViewProgMgmtComponent', () => {
let component: …Run Code Online (Sandbox Code Playgroud) 我想做一些单元测试,有一个formGroup从父组件到子组件的输入传递,如何做。
应用程序组件.ts
import { Component, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { TranslateHelper } from '@app/core/translation';
@Component({
selector: 'basic-info',
templateUrl: './'basic.component.html',
styleUrls: ['./basic.component.scss']
})
export class BasicInfoComponent {
@Input() form: FormGroup;
constructor(private translation: TranslateHelper) {
}
get w(): FormControl {
return this.form.get('y') as FormControl;
}
get x(): FormControl {
return this.form.get('x') as FormControl;
}
get y(): FormControl {
return this.form.get('y') as FormControl;
}
get z(): FormControl {
return this.form.get('z') as FormControl;
} …Run Code Online (Sandbox Code Playgroud) angular ×10
typescript ×3
unit-testing ×3
ngrx ×2
ag-grid ×1
angular10 ×1
angular8 ×1
jasmine ×1
javascript ×1
ngrx-effects ×1
promise ×1
viewchild ×1