我如何在Ionic2中测试其中有Observable调用的方法?

时间:2017-07-27 19:59:40

标签: angular unit-testing typescript ionic-framework karma-jasmine

我在测试以下方法时遇到问题:

getUserList() {
    this._user.getUsers().subscribe(list =>{
        this.user_list = list;
    });
}

测试是这样写的:

it('User list', () => {
    component.getUserList();
    fixture.detectChanges();
    expect(component.user_list.length).toBe(1);
});

但测试并没有等待方法" component.getUserList()"填充component.user_list。当我检查component.user_list值时,它是未定义的。有办法解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

您需要从方法返回promise才能进行测试,如下所示:

getUserList() {
    return this._user.getUsers().subscribe(list =>{
        this.user_list = list;
        return;
    });
}

然后在测试中:

it('User list', () => {
    component.getUserList().subscribe(res => {
       fixture.detectChanges();
       expect(component.user_list.length).toBe(1);
    });

});

答案 1 :(得分:0)

来自Rangle的

This tutorial就是一个很好的例子。

您可以为getUsers()创建模拟,为其提供TestBed并在tick内使用fakeAsync来模拟异步操作。

import { UserService } from './user.service';
import { UserComponent } from './user.component';
import { provide } from '@angular/core';
import {
  async,
  TestBed,
  fakeAsync,
  tick,
} from '@angular/core/testing';

const testUsers = [
  // Test data
];

class MockUserService {
  public users = testUsers;

  getUsers() {
    return Observable.of(this.users);
  }
}

describe('Testing User Component', () => {

  let fixture;
  let component;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        UserComponent
      ],
      providers: [
        { provide: UserService, useClass: MockUserService }
      ]
    });
    fixture = TestBed.createComponent(UserComponent);
    component = fixture.componentInstance;
  });

  it('Should get users', fakeAsync(() => {
    component.getUserList();
    tick();
    expect(component.user_list).toEqual(testUsers);
  }));
});