标签: angular2-testing

@ angular/core/testing没有导出成员'MockApplicationRef'

我想用新的RC4版本运行我的旧angular2单元测试,但我有一个问题.

MockApplicationRef发生了什么?

我应该在这里使用什么呢?

provide(ApplicationRef, { useClass: MockApplicationRef})
Run Code Online (Sandbox Code Playgroud)

angular2-testing angular

6
推荐指数
1
解决办法
789
查看次数

Angular 2单元测试可观察错误(HTTP)

我正在尝试为我的API服务编写单元测试,但在捕获HTTP错误时遇到一些问题.我遵循本指南以及Angular2文档,因为该指南在某些小范围内(稍微)过时了.

所有单元测试都与服务引发错误的单元测试分开(由于HTTP状态代码错误).我可以通过退出告诉我response.ok.从我所读到的,这与单元测试没有异步执行有关,因此,不等待错误响应.但是,我不知道为什么会出现这种情况,因为我async()beforeEach方法中使用了效用函数.

API服务

get(endpoint: string, authenticated: boolean = false): Observable<any> {
    endpoint = this.formatEndpoint(endpoint);
    return this.getHttp(authenticated) // Returns @angular/http or a wrapper for handling auth headers
        .get(endpoint)
        .map(res => this.extractData(res))
        .catch(err => this.handleError(err)); // Not in guide but should work as per docs
}
private extractData(res: Response): any {
    let body: any = res.json();
    return body || { };
}

private handleError(error: Response | any): Observable<any> {
    // TODO: Use a remote …
Run Code Online (Sandbox Code Playgroud)

unit-testing angular2-testing angular2-observables angular

6
推荐指数
1
解决办法
5636
查看次数

单元测试Angular 2 authGuard; 间谍方法没有被调用

我正在尝试对我的auth警卫服务进行单元测试.从这个答案我能够做到这一点,但现在当我为此进行单元测试时,它说Expected spy navigate to have been called.

如何让我的间谍路由器this.router在服务中使用?

AUTH-guard.service.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuardService {

  constructor(private router:Router) { }

  public canActivate() {
    const authToken = localStorage.getItem('auth-token');
    const tokenExp = localStorage.getItem('auth-token-exp');
    const hasAuth = (authToken && tokenExp);

    if(hasAuth && Date.now() < +tokenExp){
      return true;
    }
    this.router.navigate(['/login']);
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

AUTH-guard.service.spec.ts

import { TestBed, async, inject } from '@angular/core/testing';
import { RouterTestingModule } …
Run Code Online (Sandbox Code Playgroud)

unit-testing angular2-routing angular2-testing angular

6
推荐指数
1
解决办法
7406
查看次数

如何测试@ ionic/storage?

我需要测试我的服务,我正在使用@ ionic/storage来获取和设置方法中的数据.我是否需要模拟整个存储机制或者最佳实践?

ionic2 angular2-testing angular

6
推荐指数
1
解决办法
1736
查看次数

使用Jasmine进行Angular2测试,mouseenter/mouseleave-test

我有一个HighlightDirective,如果鼠标进入某个区域会突出显示,如:

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'Gainsboro';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

  private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}
Run Code Online (Sandbox Code Playgroud)

现在我想测试,如果在事件上调用(右)方法.所以像这样:

  it('Check if item will be highlighted', inject( [TestComponentBuilder], (_tcb: TestComponentBuilder) => {
    return _tcb
      .createAsync(TestHighlight)
      .then( (fixture) => {
        fixture.detectChanges();
        let element = fixture.nativeElement;
        let component = fixture.componentInstance; …
Run Code Online (Sandbox Code Playgroud)

unit-testing angular2-directives angular2-testing angular

5
推荐指数
1
解决办法
2428
查看次数

测试组件,这取决于路由参数

我有一个关于在an​​gular2中测试路由组件的问题.

这是一个简单的组件,它取决于带参数的路由'foo'.foo组件中的属性将设置为参数的值.

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';

@Component({
    selector: 'my-component',
    templateUrl: './my-component.html'
})
export class MyComponent implements OnInit
{
    foo: string;

    constructor(
        private route: ActivatedRoute
    )
    {
    }

    ngOnInit()
    {
        this.route.params.subscribe((params: Params) => {
            this.foo = params['foo'];
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想测试一下,如果使用路径创建组件,则将正确设置param.所以我想要的地方expect(component.foo).toBe('3');.

import {TestBed, ComponentFixture, async} from '@angular/core/testing';
import {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';
import {Params, ActivatedRoute} from '@angular/router';

import {Observable} from 'rxjs';

import {MyComponent} from './MyComponent';

describe('MyComponent', …
Run Code Online (Sandbox Code Playgroud)

jasmine angular2-routing angular2-testing angular

5
推荐指数
1
解决办法
4884
查看次数

当在表单中使用时,Angular2 单元测试不会更新输入的 ngModel

我在基于 Angular 2.4 的应用程序中进行了相当广泛的测试。我们尚未能够测试的一个领域是带有输入的表单。我最终将其归结为一个小测试用例。我有一个显示问题的 plnkr:https://plnkr.co/edit/NyeAoh2Uo5rJT9if6j64 (请参阅 form_bug.spec.ts)

注意:我根据测试指南中的代码的工作方式来构建此示例。

问题是,当我们将输入与 ngModel 连接起来,然后在测试套件中更新输入时,仅当输入不在表单内时,数据才会流入组件。如果我们将其添加到表单中,那么数据将无法正确流动。

代码的核心部分是:

@Component({
   selector: 'with-form-test',
   template: `
   <div>
      <div class="show_val">{{testVal}}</div>
      <form>
         <input name="test_val" id="val_id" [(ngModel)]="testVal" />
      </form>
   </div>
   `,
})
class WithFormTestComp {
   testVal: string = 'start';
}
Run Code Online (Sandbox Code Playgroud)

和测试。其中的两个 Expect() 检查失败。

describe('WithFormTest', () => {
   let fixture: ComponentFixture<WithFormTestComp>;
   let comp:    WithFormTestComp;
   let comp_de: DebugElement;

   function getInput(): DebugElement {
      return comp_de.query(By.css('input'));
   }
   function getShowVal(): DebugElement {
      return comp_de.query(By.css('.show_val'));
   }

   beforeEach(() => {
      TestBed.configureTestingModule({
         imports: [
            FormsModule,
         ],
         declarations: [
            WithFormTestComp, …
Run Code Online (Sandbox Code Playgroud)

angular2-testing angular

5
推荐指数
0
解决办法
2189
查看次数

Angular 2 - 单元测试绑定到嵌套自定义表单控件

我有一个来自 control 的自定义选择器app-date-picker。它实现了ControlValueAccessor. 我有一个名为的组件MyPage,其中包含此自定义表单控件:

<app-date-picker class="address__from-date" [(ngModel)]="fromDate"></app-date-picker>
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个单元测试来MyPage测试绑定的两个方向。我已经对其他表单字段执行了此操作,效果很好,例如:

it('should bind zip code', fakeAsync(() => {
  const formControl = element.query(By.css('.address__zip-code input')).nativeElement;

  // model -> view
  component.zipCode = 76777;
  fixture.detectChanges();
  tick();

  expect(formControl.value).toEqual('76777');

  // view -> model
  formControl.value = '89556';
  formControl.dispatchEvent(new Event('input'));

  expect(component.zipCode).toEqual(89556);
}));
Run Code Online (Sandbox Code Playgroud)

当我尝试为自定义表单控件执行此操作时,出现了问题。到目前为止,我只能测试一个绑定方向,即使如此,它也需要使用ng-reflect-model,这太糟糕了:

it('should bind from-date', fakeAsync(() => {
  const formControl = element.query(By.css('.address__from-date app-date-picker')).nativeElement;

  // model -> view
  component.fromDate = '01/2017';
  fixture.detectChanges();
  tick();

  expect(formControl.attributes['ng-reflect-model'].value).toEqual('01/2017');

  // view -> model
  // Not sure …
Run Code Online (Sandbox Code Playgroud)

unit-testing angular2-forms angular2-testing angular angular-forms

5
推荐指数
1
解决办法
3001
查看次数

如何在茉莉花测试中获取事件发射器的参数

我有一个单元测试如下

it('billing information is correct', () => {
    fixture.detectChanges();
    spyOn(component.myEventEmitter, 'emit').and.callThrough();
    component.form.controls['size'].setValue(12);
    fixture.detectChanges();
    **let args= component.myEventEmitter.emit.mostRecentCall **
    expect(args.billingSize).toEqual('30')
});
Run Code Online (Sandbox Code Playgroud)

当大小发生变化时,myEventEmitter 会与一个包含 billingSize 的大型 json 对象一起发出。我希望测试检查这个值是否符合预期。但看起来我无法在事件发射器上执行“mostRecentCall/calls”。有什么建议??

注意:我不想做

 expect(component.myEventEmitter.emit).toHaveBeenCalledWith(*dataExpected*);
Run Code Online (Sandbox Code Playgroud)

因为 dataExpected 是一个很大的 json 对象。我只关心一个领域。任何帮助将非常感激。

typescript karma-jasmine spyon angular2-testing angular

5
推荐指数
1
解决办法
5636
查看次数

Typescript 与“typeof”相反/反向操作

Angular 可以按类型查询子组件,在测试中使用它,如下所示:

fixture.debugElement.query( By.directive( ComponentType ) );
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个为我执行此操作的函数:

import { ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Type } from '@angular/core';

export function findSubComponent<T>( fixture: ComponentFixture<any>, componentType: T & Type<any> ): T {
  const subComponentDebugElement = fixture.debugElement.query( By.directive( componentType ) );
  return subComponentDebugElement.componentInstance;
}
Run Code Online (Sandbox Code Playgroud)

现在问题来了。我的函数当前返回typeof ComponentType而不是实际的对象ComponentType,因此我无法访问它的属性。

这里的 TypesubComponentDebugElement.componentInstance是 any,所以我可以在返回 Type 参数中声明类型(function (): T

typeof ComponentInstance我怎样才能将本例中代表的 T 变成ComponentInstance

typescript typescript-generics angular2-testing angular angular-test

5
推荐指数
1
解决办法
1904
查看次数