我在用RC3.我正在实现Angular2这里记录的新路由器:https://angular.io/docs/ts/latest/guide/router.html
一切正常但我在单元测试中遇到问题.具体来说,我不能将Angular2服务注入我的单元测试中.
我的相关组件代码是:
import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
templateUrl: ...
styleUrls: ...
})
export class Route1DetailComponent {
constructor(private route:ActivatedRoute) {
console.log(route);
}
}
Run Code Online (Sandbox Code Playgroud)
我的单元测试看起来像:
import {
expect, it, iit, xit,
describe, ddescribe, xdescribe,
beforeEach, beforeEachProviders, withProviders,
async, inject
} from '@angular/core/testing';
import {ActivatedRoute} from '@angular/router';
import {Route1DetailComponent} from './route1-detail.component';
import {TestComponentBuilder} from '@angular/compiler/testing';
describe('route1-detail.component.ts', () => {
beforeEachProviders(() => [
{provide: ActivatedRoute, useClass: ActivatedRoute}
]);
it('should instantiate …Run Code Online (Sandbox Code Playgroud) 我正在升级我们的Angular2应用程序以使用rc4,我开始在单元测试中出错:
无法在异步区域测试中使用setInterval
我的窗口小部件从其ngOnInit方法请求数据,并在发出请求时发出加载指示符.我的模拟服务在1ms后返回一些数据.
这是一个暴露问题的简化版本
import { inject, async, TestComponentBuilder, ComponentFixture} from '@angular/core/testing';
import {Http, Headers, RequestOptions, Response, HTTP_PROVIDERS} from '@angular/http';
import {provide, Component} from '@angular/core';
import {Observable} from "rxjs/Rx";
class MyService {
constructor(private _http: Http) {}
getData() {
return this._http.get('/some/rule').map(resp => resp.text());
}
}
@Component({
template: `<div>
<div class="loader" *ngIf="_isLoading">Loading</div>
<div class="data" *ngIf="_data">{{_data}}</div>
</div>`
})
class FakeComponent {
private _isLoading: boolean = false;
private _data: string = '';
constructor(private _service: MyService) {}
ngOnInit() {
this._isLoading = true;
this._service.getData().subscribe(data …Run Code Online (Sandbox Code Playgroud) 我正在编写自定义角度(Angular 2.0.0)验证,遵循本指南https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#custom-validation.
@Directive({
selector: '[ngModel][emailValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: EmailValidatorDirective, multi: true}]
})
export class EmailValidatorDirective implements Validator
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试将单元测试添加到我的自定义验证指令中.
beforeEach(() => {
fixture = TestBed.createComponent(EmailComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
el = de.nativeElement;
component = de.componentInstance;
emailField = de.query(By.css('input')).nativeElement;
});
Run Code Online (Sandbox Code Playgroud)
我正在访问所有这些对象,但没有人知道我输入的有效性.有没有人知道如何在单元测试中访问我的输入的NgControl,或者我如何检查有效/无效(自定义验证)输入字段.
typescript angular2-forms angular2-directives angular2-testing angular
我试图在我的组件上运行单元测试,这是路由器的输出。我已对组件所使用的路由器和服务进行了存根,并且尝试使用fixture.debugElement拉动该元素以确认测试是否正常。但是,这总是返回为NULL。
测验
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { Router } from '@angular/router';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HeroesComponent } from './heroes.component';
import { HeroService } from '../hero.service';
import { StubHeroService } from '../testing/stub-hero.service';
import { StubRouter } from '../testing/stub-router';
let comp: HeroesComponent;
let fixture: ComponentFixture<HeroesComponent>;
let de: DebugElement;
let el: HTMLElement;
describe('Component: Heroes', () => {
beforeEach( async(() => {
TestBed.configureTestingModule({
declarations: [HeroesComponent],
providers: [
{ provide: …Run Code Online (Sandbox Code Playgroud) 我试图测试一个具有ngOnDestroy()方法的组件,该方法具有所有unsubscribe()方法调用.但是,在测试时,当我运行我的测试文件(spec文件)时,它给出了错误说:
cannot read property 'unsubscribe' of undefined
Run Code Online (Sandbox Code Playgroud)
我在我的测试文件中完成了以下导入:
import { Subscription } from 'rxjs/Subscription';
Run Code Online (Sandbox Code Playgroud)
所以我认为这应该足以获得Subscription中的所有方法,但仍然存在错误.此外,我尝试将"订阅"添加到测试文件的"导入","声明"和"提供者"列表中,但仍然存在错误.
以下是代码段:
//component
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import {
NinjaService } from '../../../../ninja.service';
@Component({
selector: 'ninja-files',
templateUrl: './ninja-files.component.html',
styleUrls: ['./ninja-files.component.css']
})
export class ninjaFilesComponent implements OnInit, OnDestroy {
showNinjaFiles: boolean = true;
addFileSubscription: Subscription;
constructor(private ninjaService: NinjaService) {
........
}
ngOnInit() {
this.addFileSubscription = this.NinjaService.AddedFile$
.subscribe((fileFormat: FileFormat) => {
console.log('File being added: ' + fileFormat.fileName); } …Run Code Online (Sandbox Code Playgroud) 我有一个返回的服务功能,Observable我正在我的一个组件中使用该服务.我已经使用此处发布的技术为组件编写了单元测试.然而,奇怪的是我得到了"无法读取未定义的属性'订阅'".
被测组件:
@Component({
moduleId: module.id,
templateUrl: 'signup.component.html'
})
export class SignupComponent implements OnInit {
signupForm: FormGroup;
submitted = false;
registered = false;
constructor(public router: Router, private fb: FormBuilder, public authService: AuthService) {
this.signupForm = this.fb.group({
'firstName': ['', Validators.required],
'lastName': ['', Validators.required],
'email': ['', Validators.compose([Validators.required])],
'password': ['', Validators.compose([Validators.required])],
'confirmPassword': ['', Validators.required]
});
}
ngOnInit() {
}
signup(event: any) {
event.preventDefault();
this.submitted = true;
if (!this.signupForm.valid) return;
this.authService.register(this.signupForm.value)
.subscribe(
(res: Response) => {
if (res.ok) {
this.registered = …Run Code Online (Sandbox Code Playgroud) 假设我有一个我想要测试的组件,它使用了一个非常复杂的组件.此外,它使用获得的引用调用它的一些方法@viewChildren.例如
@Component({
moduleId: module.id,
selector: 'test',
template: '<complex *ngFor='let v of vals'></complex>' ,
})
export class TestComponent{
vals = [1,2,3,4]
@ViewChildren(ComplexComponent) cpxs : QueryList<ComplexComponent>
// ....
}
Run Code Online (Sandbox Code Playgroud)
如何在`TestBed'中替换复合组件以获得测试双?
就像是
@Component({
moduleId : module.id,
selector: 'complex', template: ''
})
class ComplexComponentStub {
}
describe('TestComponent', () => {
beforeEach( async(() => {
TestBed.configureTestingModule({
declarations : [ComplexComponentStub, TestComponent],
});
it('should have four sons',()=>{
let fixture = TestBed.createComponent(TestComponent);
let comp = fixture.componentInstance as TestComponent;
fixture.detectChanges();
expect(comp.cpxs.length).toBe(4);
});
//....
}));
Run Code Online (Sandbox Code Playgroud)
有关完整示例,请参阅plnkr http://plnkr.co/edit/ybdrN8VimzktiDCTvhwe?p=preview
我正在MockBackend测试依赖的代码@angular/http.
Web上的所有示例都使用异步测试设置,如下所示:
thoughtram:在Angular中使用Http测试服务
describe('getVideos()', () => {
it('should return an Observable<Array<Video>>',
async(inject([VideoService, MockBackend], (videoService, mockBackend) => {
videoService.getVideos().subscribe((videos) => {
expect(videos.length).toBe(4);
expect(videos[0].name).toEqual('Video 0');
expect(videos[1].name).toEqual('Video 1');
expect(videos[2].name).toEqual('Video 2');
expect(videos[3].name).toEqual('Video 3');
expect("THIS TEST IS FALSE POSITIVE").toEqual(false);
});
const mockResponse = {
data: [
{ id: 0, name: 'Video 0' },
{ id: 1, name: 'Video 1' },
{ id: 2, name: 'Video 2' },
{ id: 3, name: 'Video 3' }
]
};
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new …Run Code Online (Sandbox Code Playgroud) 基本上我有一个看起来像这样的组件:
export class CmpB extends CmpA {
variableA:any = {};
@Input() config:any = {};
constructor(private serviceA: serviceA,
@Optional() private CmpC?: CmpC) {
super();
}
ngOnInit() {
if (this.CmpC) {
super.doSomething(parameterA);
//other stuff
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我基本上得到了扩展CmpA的CmpB(根据配置改变了变量A)并且为了做某事它需要一个特定的父组件CmpC.......我需要为它编写一个实际验证CmpA突变的测试.
我的测试看起来像这样
describe('CmpB', () => {
let mock: any = MockComponent({ selector: "app-element", template: "<CmpC><CmpB></CmpB></CmpC>" });
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [mock, CmpC, CmpB],
providers: [
ServiceA
]
}).compileComponents();
});
it('CmpB component test', async(() => {
const appMock = TestBed.createComponent(mock);
appMock.detectChanges();
const el = appMock.debugElement.nativeElement …Run Code Online (Sandbox Code Playgroud) 我用茉莉花+业力编写了单元2的单元测试。
我有组件检查异常并抛出错误。并编写单元测试以检查这种情况。
但是我在触发时看到错误消息fixture.detectChanges();
“未处理的承诺拒绝:”
我该如何解决这种情况。请在下面查看我的代码。谢谢
**MyComponent.ts**
ngOnInit() {
if (this.erorr) {
throw new Error("error");
}
}
**AppModule.ts**
class MyErrorHandler extends ErrorHandler {
handleError(error) {
console.log("error");
location.href="/error"
}
}
Run Code Online (Sandbox Code Playgroud)
和一个单元测试文件
**MyComponent.spec.ts**
describe('My Management Test', () => {
beforeEach(async( () => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: provider,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: imports
}).compileComponents().then(() => {});
}));
beforeEach(inject([MockBackend], (mockBackend: MockBackend) => {
Connection(mockBackend);
fixture = TestBed.createComponent(MyComponent);
}));
it('Go to contact management page', (done) => {
fixture.detectChanges();
//Need to check if component …Run Code Online (Sandbox Code Playgroud)