在Angular 2 ngOnInit中测试承诺

时间:2016-02-15 00:40:08

标签: jasmine angular

我有一个Angular 2组件我试图进行测试,但是我遇到了麻烦,因为数据是在ngOnInit函数中设置的,所以在单元测试中不能立即使用。

用户view.component.ts:

import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';

import {User} from './user';
import {UserService} from './user.service';

@Component({
  selector: 'user-view',
  templateUrl: './components/users/view.html'
})
export class UserViewComponent implements OnInit {
  public user: User;

  constructor(
    private _routeParams: RouteParams,
    private _userService: UserService
  ) {}

  ngOnInit() {
    const id: number = parseInt(this._routeParams.get('id'));

    this._userService
      .getUser(id)
      .then(user => {
        console.info(user);
        this.user = user;
      });
  }
}

user.service.ts:

import {Injectable} from 'angular2/core';

// mock-users is a static JS array
import {users} from './mock-users';
import {User} from './user';

@Injectable()
export class UserService {
  getUsers() : Promise<User[]> {
    return Promise.resolve(users);
  }

  getUser(id: number) : Promise<User> {
    return Promise.resolve(users[id]);
  }
}

用户view.component.spec.ts:

import {
  beforeEachProviders,
  describe,
  expect,
  it,
  injectAsync,
  TestComponentBuilder
} from 'angular2/testing';
import {provide} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';

import {UserViewComponent} from './user-view.component';

import {UserService} from './user.service';

export function main() {
  describe('User view component', () => {
    beforeEachProviders(() => [
      provide(RouteParams, { useValue: new RouteParams({ id: '0' }) }),
      UserService
    ]);

    it('should have a name', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
      return tcb.createAsync(UserViewComponent)
        .then((rootTC) => {
          spyOn(console, 'info');

          let uvDOMEl = rootTC.nativeElement;
          rootTC.detectChanges();

          expect(console.info).toHaveBeenCalledWith(0);
          expect(DOM.querySelectorAll(uvDOMEl, 'h2').length).toBe(0);
        });
    }));

  });
}

路由参数正确传递,但在运行测试之前视图没有更改。如何设置在ngOnInit中的promise解决后发生的测试?

3 个答案:

答案 0 :(得分:10)

IMO这个用例的最佳解决方案是创建一个同步模拟服务。对于此特定情况use fakeAsync,您无法because of the XHR call for templateUrl。我个人认为make ngOnInit return a promise的“黑客”并不优雅。而且你不应该直接调用ngOnInit,因为它应该被框架调用。

您应该已经在使用模拟,因为您只是对组件进行单元测试,并且不希望依赖于真实服务正常工作。

要创建一个同步的服务,简单地从正在调用的任何方法返回服务本身。然后,您可以将thencatchsubscribe(如果您使用Observable)方法添加到模拟中,因此它的行为类似于Promise。例如

class MockService {
  data;
  error;

  getData() {
    return this;
  }

  then(callback) {
    if (!this.error) {
      callback(this.data);
    }
    return this;
  }

  catch(callback) {
    if (this.error) {
      callback(this.error);
    }
  }

  setData(data) {
    this.data = data;
  }

  setError(error) {
    this.error = error;
  }
}

这有一些好处。例如,它可以在执行期间为您提供对服务的大量控制,因此您可以轻松地自定义其行为。当然,这一切都是同步的。

这是另一个例子。

您将看到组件的一个常见问题是使用ActivatedRoute并订阅其参数。这是异步的,在ngOnInit内完成。我倾向于这样做是为ActivatedRoute params属性创建一个模拟。 params属性将是一个模拟对象,并且具有一些对外部世界显示的功能,如可观察的。

export class MockParams {
  subscription: Subscription;
  error;

  constructor(private _parameters?: {[key: string]: any}) {
    this.subscription = new Subscription();
    spyOn(this.subscription, 'unsubscribe');
  }

  get params(): MockParams {
    return this;
  }

  subscribe(next: Function, error: Function): Subscription {
    if (this._parameters && !this.error) {
      next(this._parameters);
    }
    if (this.error) {
      error(this.error);
    }
    return this.subscription;
  }
}

export class MockActivatedRoute {
  constructor(public params: MockParams) {}
}

您可以看到我们的subscribe方法行为类似于Observable#subscribe。我们做的另一件事是监视Subscription,以便我们可以测试它是否被销毁。在大多数情况下,您将在ngOnDestroy内取消订阅。要在测试中设置这些模拟,您可以执行类似

的操作
let mockParams: MockParams;

beforeEach(() => {
  mockParams = new MockParams({ id: 'one' });
  TestBed.configureTestingModule({
    imports: [ CommonModule ],
    declarations: [ TestComponent ],
    providers: [
      { provide: ActivatedRoute, useValue: new MockActivatedRoute(mockParams) }
    ]
  });
});

现在为路径设置了所有参数,我们可以访问模拟参数,这样我们就可以设置错误,并检查订阅间谍以确保它已取消订阅。

如果你看下面的测试,你会发现它们都是同步测试。不需要asyncfakeAsync,它会以绚丽的色彩传递。

这是完整的测试(使用RC6)

import { Component, OnInit, OnDestroy, DebugElement } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

@Component({
  template: `
    <span *ngIf="id">{{ id }}</span>
    <span *ngIf="error">{{ error }}</span>
  `
})
export class TestComponent implements OnInit, OnDestroy {
  id: string;
  error: string;
  subscription: Subscription;

  constructor(private _route: ActivatedRoute) {}

  ngOnInit() {
    this.subscription = this._route.params.subscribe(
      (params) => {
        this.id = params['id'];
      },
      (error) => {
        this.error = error;
      }
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

export class MockParams {
  subscription: Subscription;
  error;

  constructor(private _parameters?: {[key: string]: any}) {
    this.subscription = new Subscription();
    spyOn(this.subscription, 'unsubscribe');
  }

  get params(): MockParams {
    return this;
  }

  subscribe(next: Function, error: Function): Subscription {
    if (this._parameters && !this.error) {
      next(this._parameters);
    }
    if (this.error) {
      error(this.error);
    }
    return this.subscription;
  }
}

export class MockActivatedRoute {
  constructor(public params: MockParams) {}
}

describe('component: TestComponent', () => {
  let mockParams: MockParams;

  beforeEach(() => {
    mockParams = new MockParams({ id: 'one' });
    TestBed.configureTestingModule({
      imports: [ CommonModule ],
      declarations: [ TestComponent ],
      providers: [
        { provide: ActivatedRoute, useValue: new MockActivatedRoute(mockParams) }
      ]
    });
  });

  it('should set the id on success', () => {
    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    let debugEl = fixture.debugElement;
    let spanEls: DebugElement[] = debugEl.queryAll(By.css('span'));
    expect(spanEls.length).toBe(1);
    expect(spanEls[0].nativeElement.innerHTML).toBe('one');
  });

  it('should set the error on failure', () => {
    mockParams.error = 'Something went wrong';
    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    let debugEl = fixture.debugElement;
    let spanEls: DebugElement[] = debugEl.queryAll(By.css('span'));
    expect(spanEls.length).toBe(1);
    expect(spanEls[0].nativeElement.innerHTML).toBe('Something went wrong');
  });

  it('should unsubscribe when component is destroyed', () => {
    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    fixture.destroy();
    expect(mockParams.subscription.unsubscribe).toHaveBeenCalled();
  });
});

答案 1 :(得分:5)

Promise返回#ngOnInit

ngOnInit(): Promise<any> {
  const id: number = parseInt(this._routeParams.get('id'));

  return this._userService
    .getUser(id)
    .then(user => {
      console.info(user);
      this.user = user;
    });
}

几天前我遇到了同样的问题,发现这是最可行的解决方案。据我所知,它不会影响应用程序中的任何其他位置;由于#ngOnInit在源的TypeScript中没有指定的返回类型,我怀疑源代码中的任何内容都期望返回值。

指向OnInithttps://github.com/angular/angular/blob/2.0.0-beta.6/modules/angular2/src/core/linker/interfaces.ts#L79-L122

的链接

修改

在测试中,您将返回新的Promise

it('should have a name', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
  // Create a new Promise to allow greater control over when the test finishes
  //
  return new Promise((resolve, reject) => {
    tcb.createAsync(UserViewComponent)
      .then((rootTC) => {

        // Call ngOnInit manually and put your test inside the callback
        //
        rootTC.debugElement.componentInstance.ngOnInit().then(() => {
          spyOn(console, 'info');

          let uvDOMEl = rootTC.nativeElement;
          rootTC.detectChanges();

          expect(console.info).toHaveBeenCalledWith(0);
          expect(DOM.querySelectorAll(uvDOMEl, 'h2').length).toBe(0);

          // Test is done
          //
          resolve();
        });

      });
    }));

  }

答案 2 :(得分:2)

我有同样的问题,这是我设法解决它的方法。我不得不使用fakeAsync和tick。

fakeAsync(
      inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        tcb
        .overrideProviders(UsersComponent, [
          { provide: UserService, useClass: MockUserService }
        ])
        .createAsync(UsersComponent)
        .then(fixture => {
          fixture.autoDetectChanges(true);
          let component = <UsersComponent>fixture.componentInstance;
          component.ngOnInit();
          flushMicrotasks();
          let element = <HTMLElement>fixture.nativeElement;
          let items = element.querySelectorAll('li');
          console.log(items);
        });
      })
    )