david david - 3 months ago 125
AngularJS Question

using Http on angular 2 unit tests

I'm using this seed project: https://github.com/juliemr/ng2-test-seed that was recently updated to RC5 of angular.

I want to use the Http component in unit test so I did the following:

In package.json I added to dependencies:

"@angular/http": "2.0.0-rc.5",


In src/test/user-service_test.ts I added:

import { HttpModule, Http } from '@angular/http';


and modified the beforeEach function to include HttpModule:

beforeEach(() => {
TestBed.configureTestingModule({
providers: [LoginService, UserService, HttpModule]
});
});


Now, as soon as I add the HttpModule in the beforeEach function and try to execute the test I got this error:

13 08 2016 09:13:27.609:WARN [web-server]: 404: /base/node_modules/@angular/http
Missing error handler on `socket`.
TypeError: (msg || "").replace is not a function
at /home/david/Workspace/ng2-seed/node_modules/karma/lib/reporter.js:45:23
at onBrowserError (/home/david/Workspace/ng2-seed/node_modules/karma/lib/reporters/base.js:58:60)
at null.<anonymous> (/home/david/Workspace/ng2-seed/node_modules/karma/lib/events.js:13:22)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at onKarmaError (/home/david/Workspace/ng2-seed/node_modules/karma/lib/browser.js:95:13)
at Socket.<anonymous> (/home/david/Workspace/ng2-seed/node_modules/karma/lib/events.js:13:22)
at emitOne (events.js:82:20)
at Socket.emit (events.js:169:7)
at Socket.onevent (/home/david/Workspace/ng2-seed/node_modules/socket.io/lib/socket.js:335:8)
at Socket.onpacket (/home/david/Workspace/ng2-seed/node_modules/socket.io/lib/socket.js:295:12)
at Client.ondecoded (/home/david/Workspace/ng2-seed/node_modules/socket.io/lib/client.js:193:14)
at Decoder.Emitter.emit (/home/david/Workspace/ng2-seed/node_modules/component-emitter/index.js:134:20)
at Decoder.add (/home/david/Workspace/ng2-seed/node_modules/socket.io-parser/index.js:247:12)
at Client.ondata (/home/david/Workspace/ng2-seed/node_modules/socket.io/lib/client.js:175:18)
at emitOne (events.js:77:13)


I'm still not using the Http component in a "it" function, does someone know how to use Http on a unit test on Rc5? I need to reach my server services.

Answer

TestBed.configureTestingModule expects module definition object as an argument. According to the manual, imported modules are listed as imports property, it should be

TestBed.configureTestingModule({
  imports: [HttpModule],
  providers: [LoginService, UserService]
});