Unit Test Rxjs + Ngrx Subscription in Angular with Karma

Asked

Viewed 75 times

0

I’m having difficulty executing unit test for the following function:

subscribeToUsuario(): void {
    this.subscription.add(
      this.store$.pipe(select(selectors.selectUsuario)).subscribe(state => {
        if (!state || !state.usuario) return;
        this.usuario = state.usuario;
      })
    );
  }

In the Stanbul always hits as Function/statement not covered, what would be the ideal way to test this function?

  • Could you also post the contents of the unit test? The code posted is the one being tested, correct?

  • what this Subscription would be?

1 answer

1


you could do it that way:

1- inside the test suite, you would create a property for the store that contains a Spy for the pipe:

const storeMock = jasmine.createSpyObj(['pipe']);

2- create a mock that has the same return structure as your selector.

3- No providers inside your configureTestingModule you would associate your Spy with the library module in this way:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { provide: Store, useValue: storeMock },
      ]
    }).compileComponents();
  }));

4- Within your test case you would add Spy that way:

storeMock.pipe.and.returnValue(of(selectUsuarioMock));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.