【问题标题】:How can I test the data coming from server in my component test file如何在组件测试文件中测试来自服务器的数据
【发布时间】:2020-04-17 08:10:01
【问题描述】:

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

我有一个应用服务,它发出 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');
    }
}

common-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([]);
  }
}

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

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

    如下更改 MockAppService 类。

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

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

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

    【讨论】:

    • 感谢您的帮助。 :)
    猜你喜欢
    • 2020-07-16
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多