Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test Angular 2 service subject

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

And the test file for that service:

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

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.

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

like image 624
crdevdeu Avatar asked Jul 14 '17 20:07

crdevdeu


People also ask

How do I test my jasmine service?

When testing a service with a dependency, provide the mock in the providers array. In the following example, the mock is a spy object. content_copy let masterService: MasterService; let valueServiceSpy: jasmine. SpyObj<ValueService>; beforeEach(() => { const spy = jasmine.

What is fixture detectChanges ()?

fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement.

What is SpyOn in Angular unit testing?

Test the Component logic using SpyOn. SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result. This example shows how spyOn works, even if we are still mocking up our service.

What is HttpClientTestingModule?

Using the HttpClientTestingModule and HttpTestingController provided by Angular makes mocking out results and testing http requests simple by providing many useful methods for checking http requests and providing mock responses for each request.


2 Answers

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.

like image 129
pbialy Avatar answered Oct 05 '22 09:10

pbialy


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);
        });
    });
});
like image 31
Pasha Sybiriak Avatar answered Oct 05 '22 08:10

Pasha Sybiriak