angular 4 unit testing error `TypeError: ctor is not a constructor`

Aniruddha Das picture Aniruddha Das · Jun 16, 2017 · Viewed 30.2k times · Source

I am trying to test my route resolver and while testing I got TypeError: ctor is not a constructor and no idea why it happen while typescript compile time no error.

TypeError: ctor is not a constructor
TypeError: ctor is not a constructor
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42355:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42362:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at NgModuleRef_.webpackJsonp../node_modules/@angular/core/@angular/core.es5.js.NgModuleRef_.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:43401:16)
    at TestBed.webpackJsonp../node_modules/@angular/core/@angular/core/testing.es5.js.TestBed.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:48412:47)
    at http://localhost:9877/_karma_webpack_/vendor.bundle.js:48418:61
    at Array.map (native)

Answer

abahet picture abahet · Jul 6, 2017

This can be an error in the providers declarations.

When you try to mock a provider and use useClass instead of useValue the error "TypeError: ctor is not a constructor" is fired.

Here is an example that fires the error :

providers: [{provide: OrderService, useClass: new OrderServiceMock()}]

The correct declaration is :

providers: [{provide: OrderService, useValue: new OrderServiceMock()}]