如何在我的组件测试文件中测试来自服务器的数据

How can I test the data coming from server in my component test file

我正在为我获取员工列表的组件编写单元测试。

我有一个发出 http 请求的应用程序服务。 App Service 还依赖于另一个定义 http get 方法的 common-crud 服务。

我想用 testObject(在 .spec 文件中)测试我的 GET 数据,以便该对象应该等于我的数据对象之一。

我试图在我的 .spec 文件中模拟这两个服务,但我猜它们没有以正确的方式实现,因为我没有在我的 .spec 文件中获取数据。

我对此有点陌生,所以不知道如何以正确的方式实现它。

感谢您的帮助。

.ts 文件:

  ngOnInit() {
    this.getItems();
  }

  getItems() {
    this.service.getData().
    subscribe(
      response => {
        this.itemsArray = response.data;
        console.log(this.itemsArray);
      },
      error => console.log('Error: ' + error)
    );
  }

.app.service:

@Injectable()
export class AppService {

  constructor(private service: CommonCrudService) { }

    getData(): Observable<any> {
      return this.service.get('http://dummy.restapiexample.com/api/v1/employees');
    }
}

普通-crud.service.ts:

@Injectable()
export class CommonCrudService {

  constructor(private http: HttpClient) { }

  private handleError(error: any) {
    console.error(error);
    return throwError(error);
  }

  public get(url: string) {
    return this.http.get(url).pipe(
    map((response: Response) => {
      return response;
    }),
    catchError((error: Response | any) => {
      console.error(error);
      return observableThrowError(error);
    }));
  }

.spec.ts:

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
import { CommonCrudService } from './common-crud.service';
import { Observable, of } from 'rxjs';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { mockPipe } from './app-pipe.mock';

const testObject = {
  id: '1',
  employee_name: 'Tiger Nixon',
  employee_salary: '320800',
  employee_age: '61',
  profile_image: ''
};

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        mockPipe({name: 'itemSearch'})
      ],
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        {
          provide: AppService,
          useClass: MockAppService
        },
        {
          provide: CommonCrudService,
          useClass: MockCommonCrudService
        }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', async(() => {
    expect(component).toBeTruthy();
  }));

});

class MockAppService {
  getData(): Observable<any> {
    return of([]);
  }
}

class MockCommonCrudService {
  get(): Observable<any> {
    return of([]);
  }
}

您没有正确指定 return 值。如果要将 testObject 设置为 itemsArray 。您需要将应用服务中getData()函数的return值指定给​​testObject。

更改 MockAppService class 如下。

 class MockAppService {
      getData(): Observable<any> {
        return of([testObject]);
      }
    }

然后检查组件 属性 试试这样。

 it("Should test getItems()" , ()=> {
       component.getItems()
       fixture.detectChanges()
       expect(compoent.itemsArray).toEqual([testObject])
   })