Unit test Angular 2 service subject

房东的猫 提交于 2019-12-05 07:35:13

I found this article while searching for the solution:

http://www.syntaxsuccess.com/viewarticle/unit-testing-eventemitter-in-angular-2.0

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

to

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

  subjectService.callNextOnSubject('test');

, so subscribe at first, then emit an event.

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

You should test the data which changed in component after your subject is called. Should testing only public variables, not private or protected; For example:

service:

@Injectable()
export class SomeService {
    onSomeSubject: Subject<any> = new Subject();

    someSubject(string: string) {
        this.onSomeSubject.next(string);
    }
}

component:

export class SomeComponent {
    @Input() string: string;

    constructor(private service: SomeService) {
        service.onSomeSubject.subscribe((string: string) => {
            this.string = string;
        }); //don't forget to add unsubscribe.
    }
}

test:

...
describe('SomeService', () => {
    let someService: SomeService; // import SomeService on top
    let someComponent: SomeComponent; // import SomeService on top

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [SomeService, SomeComponent]
        });
        injector = getTestBed();
        someService = injector.get(SomeService);
        someComponent = injector.get(SomeComponent);
    });

    describe('someSubject', () => {
        const string = 'someString';

        it('should change string in component', () => {
            someService.someSubject(string);
            expect(someComponent.string).tobe(string);
        });
    });
});

Using jasmine 'done' callback will do the trick so far, check the documentation below: https://jasmine.github.io/api/edge/global (see implementationCallback(doneopt))

Below an example using your test case:

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

      subjectServiceProperty$.subscribe((message) => {
        expect(message).toBe('test');
        done();
      })
  }) // function returned by 'inject' has to be invoked
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!