Expected Response with status: null null for URL:

2020-05-10 09:01发布

问题:

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))

    }
}

回答1:

@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/