简体   繁体   English

如何在 angular 中使用 Subject 测试服务

[英]How to test Service with Subject in angular

this is my Service.这是我的服务。

import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { Observable } from "rxjs";
import { filter, map } from "rxjs/operators";

interface i {
  key: any;
  value: any;
}
@Injectable()
export class Srvc {
  private subject: Subject<i>;

  constructor() {
    this.subject = new Subject<i>();
  }

  next(key: any, value?: any) {
    this.subject.next({ key, value });
  }

  sub<T>(key: any): Observable<T> {
    return this.subject.asObservable().pipe(
      filter((event) => {
        return event.key === key;
      }),
      map((event) => <T>event.value)
    );
  }
}

this is my spec file这是我的规格文件

import { Observable, of, Subject } from "rxjs";
import { Injectable } from "@angular/core";
import { TestBed, inject } from "@angular/core/testing";
import { Srvc } from "./srvc.service"

interface i{
  key: any;
  value: any;
}
fdescribe("Srvc", () => {
  let service: Srvc;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      providers: [
        Srvc,
      ],
    });
  });

  it("should be created", () => {
    service = TestBed.inject(Srvc);
    expect(service).toBeTruthy();
  })

  it('should be subscribed', (() => {
    service = TestBed.inject(Srvc);
    service.next('test', "Hello World");
    service.sub<any>('test').subscribe((message: any) => {
      expect(message).toBe("Hello World")
    })
  }))
})

I am getting "SPEC HAS NO EXPECTATIONS should be subscribed".我收到“SPEC HAS NO EXPECTATIONS should be subscribed”。 I am starting with testing in angular. I am reading articles on it but cant figure out what i am doing wrong.我从 angular 开始测试。我正在阅读有关它的文章,但无法弄清楚我做错了什么。 Any suggestion will be helpful.任何建议都会有所帮助。 Thank you.谢谢你。

it('should be subscribed', ((done) => {
service = TestBed.inject(Srvc);

service.sub<any>('test').subscribe((message: any) => {
  expect(message).toBe("Hello World");
  done();
})
service.next('test', "Hello World");

})) }))

It is asynchronous so the test suite does not know when the async part is 'done'它是异步的,因此测试套件不知道异步部分何时“完成”

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

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