如何在 jasmine 测试中触发服务调用并验证输出长度?

问题描述 投票:0回答:1

问题 (1) 我无法找到在单元测试中触发服务调用的方法,该调用应该在给出输入时触发。

(2)输出的长度可以根据输入确定,并且该长度必须在单元测试中验证。

代码

    <form [formGroup]="sampleFormGroup">
        <ng-select class="default" [items]="listItems | async" bindLabel="id"
        formControlName="theList" [typeahead]="search" id="mylist">
        </ng-select>
    </form>

     export class AppComponent implements OnInit {
     search:Subject<string> = new Subject<string>();
     listItems: Observable<any>;
     testl:any;

     constructor(private formBuilder:FormBuilder,private dataService:ListService){}
     public sampleFormGroup = this.formBuilder.group({
       theList:[null]
     });

     ngOnInit(): void {
       this.listItems = this.search.pipe(
         debounceTime(500),
         switchMap(id => this.dataService.getList(id))
       );
     }
    }

    export class ListService {
     constructor(private http:HttpClient) {}

     getList(id:any) {
       return this.http.get('https://api.restful-api.dev/objects?id='+id);
     }
    }

    it(`should set the length of output observable array as 1`, () => {
        const fixture = TestBed.createComponent(AppComponent);
        const app = fixture.componentInstance;
        const list = [{"id":"3","name":"Apple"},{"id":"5","name":"Samsung"}];
        listService.getList.and.returnValue(of(list));
        component.search = new BehaviorSubject('3');
        component.listItems.subscribe(resp => {
          expect(resp.length).toBe(1);
        })
      });

预期结果 模拟列表中有 2 项。如果测试输入为 3,则输出中的列表有 1 项,这意味着输出的长度应为 1。

angular jasmine karma-jasmine
1个回答
0
投票

您必须编写函数来过滤服务上的列表。由于您正在使用异步的可观察对象(不等待期望块运行。您可以使用

done
参数在期望运行后运行。现在测试将等待订阅返回,然后仅关闭测试。

  it(`should set the length of output observable array as 1`, (done) => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    const list = [{"id":"3","name":"Apple"},{"id":"5","name":"Samsung"}];
    listService.getList = (id: any) => {
        const filtered = list.filter((item: any) => item.id === id);
        return of(filtered);
    } as any;
    component.search = new BehaviorSubject('3');
    component.ngOnInit(); // <- doing again to reinitialize the listItems property with the mocked values.
    component.listItems.subscribe(resp => {
      expect(resp.length).toBe(1);
      done();
    })
  });
© www.soinside.com 2019 - 2024. All rights reserved.