3

我的组件.ts

import { Component, OnInit } from '@angular/core';
import {FormGroup,FormControl} from '@angular/forms'
import { DataServiceService } from './data-service.service';
import {combineLatest,Observable,pipe} from 'rxjs';
import {map,tap} from 'rxjs/operators';
import {Model} from './mode';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  constructor(private dataService: DataServiceService){}
  name = 'Angular';
  myForm: FormGroup;
  observableResult$: Observable<any>;

  ngOnInit(){
    this.myForm = new FormGroup({
      localId: new FormControl()
    })

  this.observableResult$ = combineLatest(
    this.myForm.get('localId').valueChanges,
    this.dataService.getDataFromURL(),
    (localIdSelected, dataFromAPI) => ({localIdSelected,dataFromAPI})).
    pipe(map(each => this.filterData(each.dataFromAPI,each.localIdSelected)));

    this.observableResult$.subscribe(value => {
      debugger
    })

  }
  filterData(dataFromAPI,localIDSelected){
    debugger
     return dataFromAPI.filter(item => item.userId > Number(localIDSelected));
    }

}

数据.service.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http'
import {Model} from './mode';
import {Observable} from 'rxjs';
@Injectable()
export class DataServiceService {

  constructor(private http:HttpClient) { }

  getDataFromURL():Observable<Model>{
    return this.http.get<Model>('https://jsonplaceholder.typicode.com/todos');
  }

}

app.component.html

<form [formGroup]="myForm" >

<select formControlName="localId">
  <option>1</option>
  <option>2</option>
</select>

</form>

app.spec.ts

const spyFilter = spyOn(component as any, filterData).and.callThrough();

const constAPIData$ = staticDataServiceMock.getAPIData();
                    spyOn(staticDataServiceMock, 'getAPIData').and.returnValue(
                        observableOf(countryStaticData$)
                    );
component.myForm.get('localId').setValue(1);

component.observableResult$.subscribe(value => {
expect(value[0].id==21).toBeTrue();
});

静态数据模拟.ts

export class StaticDataMock{

static getAPIData(): Observable<StaticDataElements[]> {
    return [
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false
  },
  {
    "userId": 1,
    "id": 4,
    "title": "et porro tempora",
    "completed": true
  }];
  }
}

我添加了我的测试用例来覆盖 app.spec.ts 中的 combineLatest 运算符 anf filterData,但所需的代码失败了。我期望调用 filterData 失败了。combineLatest 将在 valueChange 上触发事件并从 API 获取数据。我可以在规范文件中创建模拟和 setValue,但它仍然无法正常工作。

4

1 回答 1

3

好的,为了帮助您继续进行此操作,我继续使用您迄今为止提供的数据设置了 Stackblitz。这是链接

我做了一些事情来让测试工作(有点)。

  • 我将类getAPIData()内的方法类型更改StaticDataMock为公共,以便您可以从类外调用它。
  • 我让方法 return an of(),将返回值转换为您的数据的 Observable。
  • 我猜到了您对 DataServiceService 模拟的实现,以及 Stackblitz 中的详细信息。
  • 我创建了一个 Jasmine spyObject 来拦截对getDataFromURL()服务中的调用并返回您使用StaticDataMock.
  • 我重新排列了规范中事物的调用顺序,并做了一个console.log()显示component.observableResult$从不发出的东西。

更新

根据下面的评论,上面的 Stackblitz 链接已经更新,现在正在运行。从 Stackblitz 这里是工作规范:

it('should change return of service.function1() only', () => {
    fixture.detectChanges(); 
    component.observableResult$.subscribe(value => {
        console.log('observable Emitted, value is ', value);
        expect(value[0].id==1).toBe(true); 
    });
    component.myForm.get('localId').setValue(1);
});

这样做的关键是首先设置订阅,然后在表单中发出一个新值,这将更新combineLatest()并执行subscribe().

我很高兴这有效!

于 2018-12-03T07:06:11.333 回答