我正在尝试为相对孤立的实施测试Pipe.我使用的是最新版本angular-cli(@angular2.0.0).
管道代码是:
import { Pipe, PipeTransform } from "@angular/core";
import { DatePipe, JsonPipe } from "@angular/common";
@Pipe({name: 'dataTableFormat'})
export class DataTablePipe implements PipeTransform {
// values with type 'json' are parsed to json. As a result, string values may be displayed with quotes ("<string>").
// To avoid that, we remove these quotes with this regex
private quotesExp: RegExp = /^\"|\"$/gi;
constructor(private datePipe: DatePipe, private jsonPipe: JsonPipe) {
}
transform(value: string, type: string): string { …Run Code Online (Sandbox Code Playgroud) 我创建了NG-CLI(beta.15)一个新的项目并修改了app.component.spec改变beforeEach,以一个beforeAll和它造成的测试失败,出现以下错误:
失败:无法创建组件AppComponent,因为它未导入测试模块!
我不明白这个错误意味着什么,当然为什么我会在第一时间得到它.
这是修改后的规范:
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('App: Ng2CliTest2', () => {
beforeAll(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
});
});
it('should create the app', async(() => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app works!'`, async(() => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app works!');
}));
it('should render title in a …Run Code Online (Sandbox Code Playgroud) 我是使用Angular 2的Jasmine的新手,我经常在编写Testcase并获取错误时使用TestBed对象:Please call "TestBed.compileComponents" before your test.
我该如何解决这个错误?
@Component({
moduleId:module.id,
selector: 'my-app',
templateUrl: 'app-component.html',
})
Run Code Online (Sandbox Code Playgroud) 我正在尝试spec.ts为我的应用程序创建一个.可悲的是这是使用LoadingController从ionic-angular.现在,当我尝试配置模块时,我需要为它提供LoadingController(因为它在模块的构造函数中).
我目前遇到的问题是LoadingController想要提供一个App对象/实例.(_app: App参数)
我很绝望,所以我自己问了Ionic.github#8539
但是他们关闭了我的问题,因为这是一个问题,而不是一个问题,尽管我遇到了一些他们没有回应的问题.如果这是不可能的/没有人知道如何将是一个耻辱,因为它是一个非常酷的功能,它不仅影响LoadingController,因此AlertController和ToastController也受此影响.
我的testbed配置atm:
TestBed.configureTestingModule({
declarations: [EventsPage],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [
{provide: APICaller, useValue: mockAPICaller},
{provide: NavController, useValue: mockNavController },
{provide: LoadingController, useValue: ???????}, //it seems like everything I try to enter here fails.
],
imports: [FormsModule]
});
Run Code Online (Sandbox Code Playgroud)
和EventsPage构造函数:
constructor(public apiCaller: APICaller, public navCtrl: NavController,
public loadingCtrl: LoadingController){}
Run Code Online (Sandbox Code Playgroud)
编辑:LoadingController的用法
getEvents() {
// setup a loadingscreen
let loading = this.loadingCtrl.create({
content: "Loading..."
});
// present the loadingscreen
loading.present(); …Run Code Online (Sandbox Code Playgroud) 我已链接到另一张票。此错误仅发生在测试中,并且我已导入每个链接消息的 FormsModule。我正在使用 Angular 2.2.1。
ngModel 未在“ng test”中定义我已导入 FormsModule 和 ReactiveFormsModule 无效。我已经研究这个问题24小时了,但还没有更接近。大多数与升级有关,我擦除并重新启动时遇到同样的问题,使用 nggenerate 创建时测试模板非常简单。
我使用 Angular cli 来构建我的应用程序(并重建它......),并且我添加了表单导入,因为它看起来很重要。
这是我的简单模板,请注意,它不是一个表单,而是一个 div,这没有什么区别。“ngserve”看起来很合理,所以代码理论上是正确的。
这是我的表格...
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" for='line1'>Address 1</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Line 1" id='line1' [(ngModel)]='address.line1' required>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label" for='line2'>Address 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="line2" placeholder="Line 2" [(ngModel)]='address.line2'>
</div>
</div>
<div class="form-inline">
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label" for='Suburb'>Suburb</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="suburb" placeholder="Suburb" [(ngModel)]='address.suburb'>
</div>
<div class="col-sm-2"> …Run Code Online (Sandbox Code Playgroud) 我有一个组件,当用户登录它时,路由到一个名为的网址/dashboard我正在努力弄清楚为什么我会收到以下错误.
cannot read property 'args' of undefined
Run Code Online (Sandbox Code Playgroud)
我一直在关注路由器测试的官方文档https://angular.io/docs/ts/latest/guide/testing.html#!#routed-component, 但它似乎没有帮助.我的一半问题是我不太了解文档中的所有代码.这是我对路线的单元测试
beforeEach(async(()=>{
class AuthStub{
private loggedin: boolean = false;
login(){
return this.loggedin = true;
}
};
class RouterStub{
navigateByUrl(url:string){return url;}
}
TestBed.configureTestingModule({
declarations: [ HomePageContentComponent ],
providers:[
{provide: Auth, useClass:AuthStub},
{provide: Router, useClass: RouterStub}
]
})
.compileComponents()
}));
beforeEach(()=>{
fixture = TestBed.createComponent(HomePageContentComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('.loginbtn'));
el = de.nativeElement;
fixture.detectChanges();
});
it('Should log in and navigate to dashboard', inject([Router],(router:Router)=>{
const spy = spyOn(router, 'navigateByUrl');
el.click();
const navArgs …Run Code Online (Sandbox Code Playgroud) 假设我想简单地对一个组件进行单元测试,该组件采用从路径的一部分获取的参数.例如,我的组件的ngOnInit看起来像这样:
ngOnInit() {
this.route.parent.params.switchMap((params: Params) => this.service.getProject(params['projectId']))
.subscribe((project: Project) => this.update(project));
}
Run Code Online (Sandbox Code Playgroud)
我现在该怎么做:1:设置我的测试,以便组件创建工作,所以我可以单元测试其他部分
用回答编辑 - 示例ActivatedRouteStub应该使用也有可观察的params的父进行扩展,我应该使用useClass而不是useValue(忘了改回来):
@Injectable()
export class ActivatedRouteStub {
// ActivatedRoute.params is Observable
private subject = new BehaviorSubject(this.testParams);
params = this.subject.asObservable();
// Test parameters
private _testParams: {};
get testParams() { return this._testParams; }
set testParams(params: {}) {
this._testParams = params;
this.subject.next(params);
}
// ActivatedRoute.snapshot.params
get snapshot() {
return { params: this.testParams };
}
// ActivatedRoute.parent.params
get parent() {
return { params: this.subject.asObservable() };
}
}
Run Code Online (Sandbox Code Playgroud)
2:在我的UnitTest中为projectId提供一个值?
来自angular2文档的示例似乎不适用于switchMap,甚至根本不适用(我从那里使用过ActivatedRouteStub,但到目前为止没有运气 - …
我有一个组件要测试如下:
import {Component, OnInit, Input} from "@angular/core";
@Component({
selector: 'column',
template: '<ng-content></ng-content>',
host: {
'[class]': '"col col-" + width'
}
})
export class ColumnComponent implements OnInit {
@Input() public width: number;
ngOnInit() {
if (!this.width || this.width > 12 || this.width < 1) {
this.width = 12;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我无法找到一种优雅的方式来测试<ng-content>.检查了文件,但找不到好办法.
我认为有一个测试包装器组件会有所帮助.但是comp不是使用TestContainerComponent的那个,所以测试失败了
@Component({
selector: 'test-container',
template: `<column width="12">Hello</column>`
})
export class TestContainerComponent {
}
fdescribe(`Column`, () => {
let comp: ColumnComponent;
let fixture: ComponentFixture<ColumnComponent>;
let testContainerComp: …Run Code Online (Sandbox Code Playgroud) 我似乎无法测试绑定到 Angluar2 模型的输入框。我对此有点陌生,所以请耐心等待。
我有一个非常基本的 Angular2 组件,它包含一个绑定到模型的输入框。
<form>
<input type="text" [(ngModel)]="searchTerm" name="termsearchTerm" (keyup)="search()" value=""/>
</form>
Run Code Online (Sandbox Code Playgroud)
这是后面的代码:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'sc-search',
templateUrl: 'search.component.html'
})
export class SearchComponent {
@Input() data: any;
@Output() onSearchTermChanged = new EventEmitter<string>();
private searchTerm: string;
search() {
this.onSearchTermChanged.emit(this.searchTerm);
}
}
Run Code Online (Sandbox Code Playgroud)
运行以下测试时,不断得到 Expected undefined 等于 'John'。我期待测试通过。
searchableHierarchyComponentFixture.detectChanges();
let termInputDbg = searchableHierarchyComponentFixture.debugElement.query(By.css('input[name="termsearchTerm"]'));
let input = searchableHierarchyComponentFixture.nativeElement.querySelector('input');
input.value = 'John';
let evt = document.createEvent('Event');
evt.initEvent('keyup', true, false);
termInputDbg.triggerEventHandler('keyup', null);
input.dispatchEvent(evt);
tick(50); …Run Code Online (Sandbox Code Playgroud) 我想用输入测试简单的角度组件。
所以底部的一个例子几乎没有为测试做准备,并且在一个组件中应该发生test功能模糊,它显示日志,但我在控制台中没有日志。我尝试了两种情况:获取 div 原生元素并单击它并使用blur()函数输入原生元素。在 angular 应用程序中成功发生模糊,但在测试中不起作用。我该如何解决?
@Component({
template: '<div><input [(ngModel)]="str" (blur)="testFunc($event)" /></div>'
})
class TestHostComponent {
it: string = '';
testFunc = () => {
console.log('blur!!!');
}
}
describe('blur test', () => {
let component: TestHostComponent;
let fixture: ComponentFixture<TestHostComponent>;
let de: DebugElement;
let inputEl: DebugElement;
beforeEach(() => { /* component configuration, imports... */ }
beforeEach(() => {
fixture = TestBed.createComponent(TestHostComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
inputEl = fixture.debugElement.query(By.css('input'));
fixture.detectChanges();
})
it('test', async(() => {
const …Run Code Online (Sandbox Code Playgroud) angular ×10
angular2-testing ×10
jasmine ×3
unit-testing ×3
angular-cli ×1
ionic2 ×1
mocking ×1
testing ×1