在茉莉花测试中如何在角度组件类中调用Observable的“订阅”?

时间:2019-07-08 14:12:26

标签: angular jasmine observable karma-jasmine

我正在尝试测试一个组件,该组件调用Service内的方法,该方法调用Http调用以获取数据。尝试运行测试时,observable方法从不发出数据,也不会通过断言表明数据未定义。

我尝试使用FakeAsyncflushtick甚至Jasmine-Marbles模拟一个时间间隔,以等待Observable发出数据然后进行测试。

uploads.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class UploadsService {

  product: string;
  BASE_URL: string;

  constructor(private http: HttpClient, @Inject('user') private user: any) 
  {
    this.product = user.product;
    this.BASE_URL = `/upload/${this.product}/`;
  }

  retrieve(): Observable<any> {
    return this.http.get(this.BASE_URL + '/getFileList');
  }
}

uploads.component.ts

@Component({
  selector: 'app-uploads',
  templateUrl: './uploads.component.html',
  providers: [UploadsService]
})
export class UploadsComponent {

  isLoading: boolean = true;
  fileList;
  asOfDate;

  constructor(private uploadsService: UploadsService) {}

  public retrieveFiles() {
    this.uploadsService
      .retrieve()
      .finally(() => {
        this.isLoading = false;
      })
      .subscribe(
        data => {
          this.fileList = data['fileList'];
          this.asOfDate = data['asofDate'];
        },
        error => {
          console.log('Error Occurred!');
        }
      );
  }
}

uploads.component.spec.ts

function mockUser() {
  return {
    product: 'stackoverflow'
  }
}

describe('Uploads Component', () => {

    let component: UploadsComponent;
    let fixture: ComponentFixture<UploadsComponent>;
    let service: UploadsService;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
        declarations: [UploadsComponent],
        providers: [
          { provide: 'user', useValue: mockUser },
          { 
            provide: UploadsService,
            useValue: new UploadsService(null, mockUser)//is this right to do?
          }
        ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
      }).compileComponents();
    }));

    beforeEach(() => {
      fixture = TestBed.createComponent(UploadsComponent);
      component = fixture.componentInstance;
      service = TestBed.get(UploadsService);
    });

    // Tests that failed
    it('service retrieve method was called', () => {
      spyOn(service, 'retrieve');
      component.retrieveFiles();
      expect(service.retrieve).toHaveBeenCalled();
    });

    it('retrieve returns expected asOfDate', () => {
      spyOn(service, 'retrieve')
        .and.returnValue(Observable.of({ asOfDate: '7/7/2019'}));
      component.retrieveFiles();
      expect(component.asOfDate).toBe('7/7/2019'); //asOfDate was 'undefined'
    })
});

我试图用来测试retrieveFiles中的UploadsComponent方法的两个基本单元测试用例都失败了。

我尝试使用以下方法: 1)fixture.detectChanges() 2)使用FakeAsynctick模拟时间流逝。

这些解决方案对我来说还没有解决。任何线索都会很棒。

0 个答案:

没有答案