简体   繁体   English

Angular - 组件中订阅功能的单元测试

[英]Angular - unit test for a subscribe function in a component

Angular 4 unit test for a subscribe.订阅的 Angular 4 单元测试。

I want to test that my subscribe returns an array of Users.我想测试我的订阅是否返回一组用户。 I want to mock a list of users and test a function called getUsers .我想模拟一个用户列表并测试一个名为getUsers的函数。

The subscribe unit test doesnt work.订阅单元测试不起作用。 Something wrong with the syntax.语法有问题。

This is my Users interface:这是我的用户界面:

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

This is my component I want to test:这是我要测试的组件:

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;
    });
  }
}

This is my unit test attempt:这是我的单元测试尝试:

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);
    });
  }));
});

You need this for version rxjs@6 and above.对于rxjs@6及更高版本,您需要这个。 For older rxjs version answer is below:对于较旧的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);
}));

For old rxjs version change import from:对于旧的 rxjs 版本更改导入:

import { of } from 'rxjs';

to

import { of } from 'rxjs/observable/of';

I had similar issue and to make it work I used the arbitrary function (in the following code it's named done ) inside of it我有类似的问题,并使其工作我使用的任意函数(下面的代码它的命名done )在的内部


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

    // Act
    homeComponent.getUsers();

    fixture.detectChanges();
    fixture.whenStable().subscribe(() => {
        expect(homeComponent.listOfUsers).toEqual(response);
        done();
    });
  }));

in your case you can use fakeAsync also used tick() to detect change.在您的情况下,您可以使用 fakeAsync 也可以使用 tick() 来检测更改。 you can add time to tick also to indicate how log to wait.您还可以添加时间来打勾,以指示如何记录等待。 eg tick(1000)例如滴答(1000)

Code is modified from Sharikov Vladislav代码修改自 Sharikov Vladislav

import { fakeAsync, getTestBed, TestBed, tick } from '@angular/core/testing';

it("should call getUsers and return list of users", fakeAsync(() => {
  const response: User[] = [];
  spyOn(userService, 'getUsers').and.returnValue(of(response))
  homeComponent.getUsers();
  tick();
  expect(homeComponent.listOfUsers).toEqual(response);
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM