1

New to both Angular 2 and core testing.

I have a MovieComponent that uses a injected MovieService. Trying to learn, so used route params. Code is working as expected.

describe('MovieComponent', () => {
let component: MovieComponent;
let fixture: ComponentFixture<MovieComponent>;
let options: RequestOptions;
beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ MovieComponent ],
imports: [
HttpModule
],
providers: [
{
  provide: ActivatedRoute, useValue: {
  params: Observable.of({ movieName: 'Bah' })
  }
}, MovieService, Http, {provide: ConnectionBackend},
],
   schemas :[NO_ERRORS_SCHEMA ]
 })
.compileComponents();
}));

beforeEach(() => {
 options = new RequestOptions({method: RequestMethod.Get});
 fixture = TestBed.createComponent(MovieComponent);
 component = fixture.componentInstance;
 fixture.detectChanges();
});

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

But, I'm getting this test error:

TypeError: Cannot read property 'getMovies' of undefined

Thanks in advance.

user2693135
  • 1,206
  • 5
  • 21
  • 44
  • I assume your movie service has a method called getMovies. And whatever object you are passing in does not have that method. May I suggest you mock the movie service and provide your own value or class (useClass or useValue). You are only testing the component anyway, so you probably should mock the service.. – Maccurt Oct 31 '17 at 16:13
  • also is your movie service return an observable or promise? – Maccurt Oct 31 '17 at 16:14

1 Answers1

0

Are you running it in a compiler? Does it compile? I dont think that { provide:MovieService }is right. Just pass MovieService like below:`

providers: [
  {
      provide: ActivatedRoute, useValue: {
      params: Observable.of({ movieName: 'Bah' })
      }
    }, MovieService
  ]

`

gpanagopoulos
  • 2,842
  • 2
  • 24
  • 19
  • I am using typescript with Angular CLI to build, test, and run. I edited the test code above as per your suggestion, and also had to include few providers, as the test errored - ConnectionBackend, Http, Now th error says "TypeError: Cannot read property 'createConnection' of undefined" – user2693135 May 19 '17 at 16:27
  • Now you ve got the same issue but with ConnectionBackend. – gpanagopoulos May 20 '17 at 09:32
  • To give you an idea of how Unit Tests work in Angular 2, you have to build the Test module and Component the same way that you do it in your AppModule. However this will be an overkill in Test context and you should use mock dependencies/services instead. I recommend that you read the below article on how to test component with dependency: https://angular.io/docs/ts/latest/guide/testing.html#!#component-with-dependency – gpanagopoulos May 20 '17 at 09:39