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

≡放荡痞女 提交于 2019-12-02 13:59:24

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!