Null backend connection in Angular4 unit test

27 views
Skip to first unread message

OlegKon

unread,
Oct 20, 2017, 12:40:22 AM10/20/17
to Angular and AngularJS discussion

Hi,


I am trying to write a unit test (in Ang4) trying to test connection to search for some data, a single test in spec.ts 

It gives me error: TypeError: null is not an object (evaluating 'backend.connections')


Here is a snippet of my code:

it('Test Search', () => { 

backend.connections.subscribe((connection: MockConnection) => {

 let options = new ResponseOptions({ body: JSON.stringify(searchData) }); 

connection.mockRespond(new Response(options)); }); 

component.ngOnInit(); 

component.searchTerm = "test"; 

component.getData(); 

expect(component.data.length).toBeGreaterThan(0); });

I tried to add the SearchModule to imports of BeforeEach (SearchComponent declared in that SearchModule). Got another error:

"Error: Type SearchComponent is part of the declarations of 2 modules: SearchModule and DynamicTestModule! Please consider moving SearchComponent to a higher mo dule that imports SearchModule and DynamicTestModule. You can also create a new NgModule that exports and includes PolicyPortalComponent then import that NgModule in SearchModule and DynamicTestModule. (line 16032)"


Please advise. 

(I am fairly new to Jasmine and Karma)


TIA, 

Oleg

OlegKon

unread,
Nov 10, 2017, 7:55:05 PM11/10/17
to Angular and AngularJS discussion
Update: I tried to put some console outputs there:
 it seems that the second beforeEach block which supposed to inject MockBackend (see code snippet below) is not getting executed.
 The first beforeEach block contains TestBed.configureTestingModule, so must be there. 
Is it normal to have 2 beforeEach blocks? 
Maybe one should explicitly call another? 
Please advise.      
let backend: MockBackend = null; 
and will get injected: 
beforeEach(inject([..., MockBackend], (..., mockBackend: MockBackend) => { backend=mockbackend; }));
Reply all
Reply to author
Forward
0 new messages