Angular 测试 - 不能 运行 订阅内断言

Angular testing - cannot run assertion inside subscribe

我想测试一个服务,它有一个 returns 可观察的方法,但是当 运行 a expect inside subscribe

Error: Timeout - Async function did not complete within 5000ms (set by 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();
    });
  });
});

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

您的问题是调用顺序错误。

因为是先发送事件再订阅,实际上应该是先订阅再发送事件。

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

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