角度测试-无法在订阅中运行断言

时间:2020-04-02 14:00:15

标签: angular unit-testing karma-jasmine

我想测试一种服务,该服务的方法返回一个可观察到的值,但是在expect内运行subscribe时却不断出现此错误

错误:超时-异步功能未在5000毫秒内完成(由 jasmine.DEFAULT_TIMEOUT_INTERVAL)

我试图增加Jasmine的超时间隔,但这没有用。这是我的代码:

user.service.ts:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  subject: Subject<string> = new Subject<string>();

  constructor() { }

  sendUserNotification(message: string): void {
    this.subject.next(message);
  }

  getUserNotification(): Observable<string> {
      return this.subject.asObservable();
  }

}

user.service.spec.ts:

import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';

describe('UserService', () => {
  let service: UserService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(UserService);
  });

  it('should be able to set and get the registered user', (done) => {
    service.sendUserNotification('testNotification');
    service.getUserNotification().subscribe((notification: string): void => {
      expect(notification).toEqual('testNotification1');   //  This is causing the error
      done();
    });
  });
});

请告知可能出什么问题。谢谢!

1 个答案:

答案 0 :(得分:1)

您的问题是您按错误的顺序拨打电话。

因为您要先调度事件然后再进行订阅,实际上,您应该先订阅然后再调度事件。

在简历上,您需要在规范文件中执行以下操作:

import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';

describe('UserService', () => {
  let service: UserService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(UserService);
  });

  it('should be able to set and get the registered user', (done) => {
    service.getUserNotification().subscribe((notification) => {
      expect(notification).toEqual('testNotification1');
      done();
    });
    service.sendUserNotification('testNotification');
  });
});