本文介绍了单元测试Angular 2服务主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为角度服务编写测试,该服务具有Subject属性和在该主题上调用.next()的方法。该服务如下:

I'm trying to write a test for an angular service which has a Subject property and a method to call .next() on that subject. The service is the following:

@Injectable()
export class SubjectService {
  serviceSubjectProperty$: Subject<any> = new Subject();

  callNextOnSubject(data: any) {
    this.serviceSubjectProperty$.next(data);
  }
}

该服务的测试文件:

import { TestBed, inject } from '@angular/core/testing';

import { SubjectService } from './subject.service';

describe('SubjectService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        SubjectService
      ]
    });
  });

  it('callNextOnSubject() should emit data to serviceSubjectProperty$ Subject',
    inject([SubjectService], (subjectService) => {
      subjectService.callNextOnSubject('test');

      subjectServiceProperty$.subscribe((message) => {
        expect(message).toBe('test');
      })
  }));
});

如果我将subjectService.callNextOnSubject的参数从'test'更改为其他任何内容,则测试总是传递事件。我也尝试用async和fakeAsync包装所有内容,但结果是一样的。

The test always passes event if i change the argument of subjectService.callNextOnSubject from 'test' to anything else. I have also tried wrapping everything with async and fakeAsync, but the result is the same.

测试callNextOnSubject是否向serviceSubjectProperty $发送数据的正确方法是什么?主题?

What would be the correct way to test if callNextOnSubject is emitting data to the serviceSubjectProperty$ Subject?

推荐答案

我在搜索解决方案时发现了这篇文章:

I found this article while searching for the solution:

它对我来说效果很好(它很短,不要害怕打开它) 。

and it worked well for me (it's very short, don't be afraid to open it).

我在这里粘贴它可能会帮助那些来到这个网站寻找答案的人。

I'm pasting it here so maybe it will help those which came to this site looking for answer.

关于提出的问题 - 我认为您需要更改:

Regarding the question asked - I think that you need to change:

  subjectService.callNextOnSubject('test');

  subjectServiceProperty$.subscribe((message) => {
    expect(message).toBe('test');
  })

  subjectServiceProperty$.subscribe((message) => {
    expect(message).toBe('test');
  })

  subjectService.callNextOnSubject('test');

,所以先订阅,然后发出一个事件。

, so subscribe at first, then emit an event.

如果在订阅之前发出'test',那么什么都不会捕获该事件。

If you emit 'test' before subscription, then nothing will "catch" that event.

这篇关于单元测试Angular 2服务主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:36