user5260143
user5260143

Reputation: 1096

angular 2 component with ngrx - errors when run unit-testing

I'm working on angular 2 project, using ngrx (for Redux logic) and rxjs (for observable).

Now I try to testing the project by running the auto-created .spec.ts files.

Some of the testings are fail, all of them are testing of components which use Store (from ngrx). Here is one of them:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { MyComponent } from './overlay-menu-item.component';

describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ MyComponent ],
  })
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should create', () => {
  expect(component).toBeTruthy();
});
});

I look after the problem, the error was:

No provider to Store

So I add: (I use jasmine for testing)

 beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  providers: [Store]
 })
 .compileComponents();
}));

Now I got other error:

No provider for StateObservable

So I add:

  beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  providers: [Store, StateObservable]
 })
 .compileComponents();
}));

But now I got new error that I don't know what do to with it:

Failed: Can't resolve all parameters for StateObservable: (?).
    Error: Can't resolve all parameters for StateObservable: (?).
        at syntaxError [mywebprojectPath]/node_modules/@angular/compiler/@angular/compiler.es5.js:1689:22)

What should I do?

Upvotes: 3

Views: 1050

Answers (1)

amu
amu

Reputation: 778

You should create a MockStore.

In short:

import { Action } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { map } from 'rxjs/operator/map';

export class MockStore<T> extends BehaviorSubject<T> {  
  constructor(private _initialState: T) {
    super(_initialState);
  }
  dispatch = (action: Action): void => {
  }

  select = <T, R>(pathOrMapFn: any, ...paths: string[]): Observable<R> => {
    return map.call(this, pathOrMapFn);
  }
}

Then you can provide the mockStore in you tests:

const initialState = {...};
TestBed.configureTestingModule({
  ...
  providers:[
    {provide:Store, useValue: new MockStore(initialState)}
  ]
  ...
})

Upvotes: 4

Related Questions