角度4 - 单元测试组件中的订阅功能

问题描述 投票:9回答:1

订阅的Angular 4单元测试。

我想测试我的订阅返回一个用户数组。我想模拟一个用户列表并测试一个名为getUsers的函数。

订阅单元测试不起作用。语法有问题。

这是我的用户界面:

export interface User {
  id: number;
  name: string;
  username: string;
  email: string;
  address: {
    street: string;
    suite: string;
    city: string;
    zipcode: string;
    geo: {
      lat: string;
      lng: string;
    }
  };
  phone: string;
  website: string;
  company: {
    name: string;
    catchPhrase: string;
    bs: string;
  };
};

这是我要测试的组件:

import { Component, OnInit } from "@angular/core";
import { Observable } from "rxjs/Observable";

import { UserService } from "../../services/user.service";
import { User } from "../../models/user.model";

@Component({
  selector: "home-users",
  templateUrl: "./home.component.html"
})

export class HomeComponent implements OnInit {
  private listOfUsers: User[];

  constructor(private userService: UserService) {
  }

  ngOnInit() {
    this.getUsers();
  }

  getUsers(): void {
    this.userService.getUsers().subscribe(users => {
      this.listOfUsers = users;
    });
  }
}

这是我的单元测试尝试:

import { TestBed, async, inject } from "@angular/core/testing";
import { HttpModule } from "@angular/http";

import { HomeComponent } from "./home.component";
import { UserService } from "../../services/user.service";
import { User } from "../../models/user.model";

describe("HomeComponent", () => {
  let userService;
  let homeComponent;
  let fixture;
  let element;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        HomeComponent
      ],
      providers: [
        UserService
      ],
      imports: [HttpModule]
    }).compileComponents();
  }));

  beforeEach(inject([UserService], s => {
    userService = s;
    fixture = TestBed.createComponent(HomeComponent);
    homeComponent = fixture.componentInstance;
    element = fixture.nativeElement;
  }));

  it("should call getUsers and return list of users", async(() => {
    // Arrange
    let response: User[] = [];

    // Act
    homeComponent.getUsers();

    fixture.detectChanges();
    fixture.whenStable().subscribe(() => {
        expect(homeComponent.listOfUsers).toEqual(response);
    });
  }));
});
angular unit-testing jasmine karma-jasmine
1个回答
25
投票

你需要这个(对于版本rxjs 6+,旧版本的答案如下):

import { of } from 'rxjs';

it("should call getUsers and return list of users", async(() => {
  const response: User[] = [];

  spyOn(userService, 'getUsers').and.returnValue(of(response))

  homeComponent.getUsers();

  fixture.detectChanges();

  expect(homeComponent.listOfUsers).toEqual(response);
}));

对于旧的rxjs版本更改导入:

import { of } from 'rxjs';

import { of } from 'rxjs/observable/of';
© www.soinside.com 2019 - 2024. All rights reserved.