-1

I am using angular7 and doing unit testing in jasmine and karma. And I am facing error -

Error: Expected Response with status: null null for URL: null to equal 'Project11'.

My packages versions are -

"@types/jasmine": "~2.8.6", "@types/jasminewd2": "~2.0.3", "@types/jquery": "^3.3.22", "@types/node": "~8.9.4", "codelyzer": "~4.2.1", "jasmine-core": "~2.99.1", "jasmine-spec-reporter": "~4.2.1", "karma": "~1.7.1", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~1.4.2", "karma-jasmine": "~1.1.1", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "^5.4.1", "ts-node": "~5.0.1", "tslint": "~5.9.1", "typescript": "~3.1.3"

Testing - Can't resolve all parameters for (ClassName)

import { inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {
  Http, HttpModule, XHRBackend, ResponseOptions,
  Response, BaseRequestOptions
} from '@angular/http';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA} from '@angular/core';;


fdescribe('ProjectManagementComponent', () => {
  let comp: ProjectManagementComponent;
  let fixture: ComponentFixture<ProjectManagementComponent>;
  let de: DebugElement;
  let el: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProjectManagementComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      imports: [HttpClientModule, RouterTestingModule, RouterModule, NgbModule, NgxPaginationModule, FormsModule, ReactiveFormsModule, BrowserModule,],
      providers: [{ provide: ProjectManagementServiceStub, useClass: ProjectManagementServiceStub },
      { provide: ProductsService, useClass: ProductsService }, {
        provide: HttpClient,Http, useFactory: (backend, options) => {
          return new Http(backend, options);
        },
        deps: [MockBackend, BaseRequestOptions]
      },
        MockBackend,
        BaseRequestOptions,ProjectManagementService
      ]
    }) .compileComponents()

  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(ProjectManagementComponent);
    comp = fixture.componentInstance;

    fixture.nativeElement.querySelectorAll('button');
  }));

  it('should create component', () => {
    fixture = TestBed.createComponent(ProjectManagementComponent);
    comp = fixture.componentInstance;
    expect(comp).toBeTruthy();
  });


  it('should get value of toEqual', async(inject([ProjectManagementServiceStub, MockBackend],
    (service: ProjectManagementServiceStub, backend: MockBackend) => {

      backend.connections.subscribe((conn: MockConnection) => {
        const options: ResponseOptions = new ResponseOptions({ body: 'Project11' });
        conn.mockRespond(new Response(options));
      });

      service.getProject("http://192.168.5.140:3002/api/project/").subscribe(res => {
        console.log("Subscription called")
        expect(res).toEqual('Project11')
      })
    })))
});

app.component.service.stub.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { config } from "config";
import { Observable } from "rxjs";
const baseUrl: string = config.url;

@Injectable()
export class ProjectManagementServiceStub {
    constructor(private http: HttpClient) { }

    getProject(url) :Observable<any>{

        return this.http.get(url )
            .pipe(map(Response => Response))

    }
}
Techdive
  • 997
  • 3
  • 24
  • 49
  • 1
    You are over complicating it and not doing it right. Share your `component` code. I would highly recommend [this beginner article which I wrote](https://medium.com/@shashankvivek.7/say-hi-to-jasmine-karma-in-angular-intro-d728d669a1c7) and [this specific article for this question](https://medium.com/@shashankvivek.7/testing-a-component-with-stub-services-and-spies-in-jasmine-1428d4242a49) . – Shashank Vivek Aug 28 '19 at 11:22
  • Try to understand the essence of `unit testing` before directly jumping into it, otherwise it would be of not much use ,no matter how much time you put into it :) . Update the question with component code , if you need further help after reading those articles , and your new `spec` code – Shashank Vivek Aug 28 '19 at 11:24
  • Also, it looks like you want to test the ProjectManagementService getProject() method. But actually, you are providing a stub service as the object under test. Your question does not contain the code of the stub service which makes it hard to give any advice. – Stevy Aug 28 '19 at 11:27
  • @Stevy. I added the component service stub also. Kindly check. – Techdive Aug 28 '19 at 11:51
  • Your test setup suggests you are testing ProjectManagementComponent while in reality you are trying to test a service method. Then, actually, you are testing a stub class when you should test your real service class. One more thing I noticed is you are using deprecated angular/http which you should replace by angular/common/http. See https://angular.io/guide/http#testing-http-requests – Stevy Aug 28 '19 at 12:12
  • I want to test all... Component which has services from the component.service.ts file and since services..which i tried to test from service.ts file but I saw that you need to create a stub for it. So i did it. Can't we test all in one ? – Techdive Aug 28 '19 at 12:47
  • You might want to create stubs for the _dependencies_ of your object under test, not for the object itself. Apart from that, you should keep your unit tests for the component and the service in separate files following the [Angular project structure](https://angular.io/guide/file-structure) – Stevy Aug 28 '19 at 12:51
  • @Stevy . You might want to create stubs for the dependencies of your object under test, not for the object itself. - Means ? – Techdive Aug 28 '19 at 12:54
  • Also, My Component has nested services call to avoid them being in async. So how do i test the methods (/ functions ) in the component. ? – Techdive Aug 28 '19 at 12:59
  • Unit testing means you stub/mock dependencies of the unit under test. In your example, if you wanna test ProjectManagementService you mock its dependency HttpClient. If you wanna test ProjectManagementComponent you mock its dependencies (most likely ProductsService and ProjectManagementService). – Stevy Aug 29 '19 at 14:46

1 Answers1

0

@Stevy and Shashank, Thanks for your advice. I created a separate service.spec.ts file and tested the service like this -

fdescribe('ProjectManagementServiceStub', () => {
  let service: ProjectManagementServiceStub;
  let httpMock: HttpTestingController;
  beforeEach(()=>{

      TestBed.configureTestingModule({ providers : [
          ProjectManagementServiceStub] , 

        imports: [HttpClientModule, HttpClientTestingModule,RouterTestingModule, RouterModule, NgbModule, NgxPaginationModule, FormsModule, ReactiveFormsModule, BrowserModule,]
        ,})

        service = TestBed.get(ProjectManagementServiceStub);
        httpMock = TestBed.get(HttpTestingController);
  })


  it("should be initialized ", inject([ProjectManagementServiceStub], (service1:ProjectManagementServiceStub)=>{
      expect(service1).toBeTruthy();
  }));

  it("should fetch data asynchronously", 
     fakeAsync(
         inject(
             [ProjectManagementServiceStub, HttpTestingController],
             (service1: ProjectManagementServiceStub, backend : HttpTestingController)=>{
const url = "http://192.168.x.xxx:3002/api/project/";
const responseObject :any[]= [{
    projectId: "ID123",
    name: 'Project1'
}]
let response = null;

service1.getProject().subscribe(
    (receivedResponse : any) =>{
        response = receivedResponse;
        console.log("Response = ", response)  


        expect (response).toEqual(responseObject);
        expect(receivedResponse.length).toBe(1);
    },
    (error: any) =>{}
);

const requestWrapper = backend.expectOne({url :"http://192.168.x.xxx:3002/api/project/" });


expect (requestWrapper.request.method). toEqual('GET');
expect(requestWrapper.cancelled).toBeFalsy();

requestWrapper.flush(responseObject)

             }
         )
     ))

     afterEach(() => {
        httpMock.verify();
    });

});

courtsey - https://blog.knoldus.com/unit-testing-of-angular-service-with-httpclient/

https://alligator.io/angular/testing-httpclient/

Techdive
  • 997
  • 3
  • 24
  • 49
  • Hi Stevy. Yeah this is working . However, now I have queries in the component - https://stackoverflow.com/questions/57769446/unexpected-value-undefined-imported-by-the-module-dynamictestmodule-in-jasmi – Techdive Sep 03 '19 at 10:17