简体   繁体   中英

How to write unit test case for service page in angular?

How to write test cases for the service page, jasmine? I have tried writing the unit test for below function.

service.page.ts

    get(): Observable<Array<modelsample>> {
        const endpoint = "URL" ;

        return this.http.get<any>(endpoint)
          .pipe(
            map((item) => {
              return item.data.items.map(item => {
                return new department(item.name, item.id, item.isActive)
              })
            })
          )
      };

I wrote

service.spec.ts

     it('should retrieve list of  via GET ', (done) => {
    
        const dummydata: APIResponse<modelsample> = {
          isSuccess: true,
          message: 'Departments retrieved successfully',
          data: [
            {
              name: 'string',
              id: 8,
              isActive:true
            },
            {
              name: 'string',
              id: 8,
              isActive:true
            },
    
          ]
    
        };
    
        expect(service.get).toBeTruthy(); 
        service.get().subscribe((data) => {
         expect(data.length).toBe(2);
          expect(data).toEqual(dummydata.data);
          done();
        });
    
        const request = httpMock.expectOne('url');
        expect(request.request.method).toEqual('GET');
        request.flush(dummydata.data);
       
      });

this is my API response interface

export interface APIResponse<T> {
    isSuccess: boolean;
    message: string;
    errorCode?: string;
 data?:T[];
}


 

I am getting the error "map" undefined"

Your dummy data is not correct. It expects an items property on the data object. ( item.data.items.map )

You should look into making it something like:

const dummydata: APIResponse<modelsample> = {
  // ...
  data: {
    items: [
      {
        name: 'string',
        id: 8,
        isActive:true
      },
      {
        name: 'string',
        id: 8,
        isActive:true
      },
    ]
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM