Angular - 组件中订阅函数的单元测试

标签 angular unit-testing jasmine karma-jasmine

订阅的 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);
    });
  }));
});

最佳答案

rxjs@6 及以上版本需要这个。对于旧的 rxjs 版本,答案如下:

    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';

关于Angular - 组件中订阅函数的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45839955/

相关文章:

node.js - Angular 5 net::ERR_UNKNOWN_URL_SCHEME 用于来自 express 服务器的图像

angular - 数字不断产生 ionic 3

angular - 自定义表单控件未显示 mat-error

javascript - 我什么时候需要在 Jasmine 中使用 beforeEach block ?

javascript - 具有深层组件层次结构的 Angular 组件输出/事件

javascript - 配置实习生以设置/拆卸我的服务器模拟

c# - 内存库模式和单元测试

unit-testing - 什么时候在单元测试期间使用模拟对象而不是使用 stub ?

javascript - 单元测试 - 通量和数据持久性

javascript - Jasmine 和 Angular : Injecting a service into a service mock