Angular Testing - 无法在订阅内运行断言

标签 angular unit-testing karma-jasmine

我想测试一个具有返回可观察值的方法的服务,但在 subscribe 内运行 expect 时不断收到此错误

Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

我尝试增加 Jasmine 的超时间隔,但这不起作用。这是我的代码:

用户.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();
  }

}

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

关于 Angular Testing - 无法在订阅内运行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60993368/

相关文章:

unit-testing - 验证单元测试实际上正在运行,而不是因为写得不好而跳过

c# - 正确模拟泛型方法

Angular 2单元测试: There is no directive with "exportAs"

javascript - Firebase 在加载 View 之前未接收数据 - 在填充之前返回空数组

reference - Ionic 2 Cordova网络信息插件引用错误

node.js - NPM安装显示错误

angular - Kendo Grid Persist State 破坏了可编辑的弹出窗口功能

c# - 如何强制 MSTEST TestMethod 在运行前重置所有单例/静态?

javascript - 测试 $state.go 在 Angular JS 规范中给出错误

javascript - 无法设置未定义错误的属性 '$submitted' - Jasmine AngularJS