简体   繁体   English

角度-单元测试Subject()?

[英]Angular - Unit testing Subject()?

I have a Angular service that simply uses a Subject, but I am unsure of how to write unit tests for it. 我有一个仅使用Subject的Angular服务,但是我不确定如何为它编写单元测试。

I saw [this thread][1], but I didn't find it terribly helpful. 我看到了[this thread] [1],但没有发现它有很大帮助。

I have attempted to mock next() but I am more than a little lost. 我试图模拟next()但是我迷失了不少。

You should spy on service.serviceMsg and not service , because next() method appears to be on serviceMsg subject. 您应该监视service.serviceMsg而不是service ,因为next()方法似乎在serviceMsg主题上。

it('should catch what is emitted', () => {
    const nextSpy = spyOn(service.serviceMsg, 'next');
    service.confirm(ACTION);
    expect(nextSpy).toHaveBeenCalled();
});

EDIT : 编辑:

You should also change the way you are creating service instance. 您还应该更改创建service实例的方式。 What you show in your code is applicable only for component instance creation 您在代码中显示的内容仅适用于component实例创建

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [MessageService]
    });
    service = TestBed.get(MessageService); // get service instance
    httpMock = TestBed.get(HttpTestingController);
});

Firstly you can just subscribe to your Subject and inside expect some value and after that just execute method which will emit that: 首先,您可以只订阅您的Subject并在其中期望一些值,然后执行该方法即可发出该值:

it('should catch what is emitted', () => {
    service.serviceMsg.subscribe(msg => {
        expect(msg).toEqual(something);
    });
    service.confirm(value); // this should match what you expect above
});

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

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