测试在订阅服务器中设置的属性的值

时间:2020-09-27 05:07:45

标签: angular rxjs jasmine

我正在使用Jasmine测试Angular应用程序,并且试图弄清楚如何测试组件内Observable的subscribe调用中设置的属性的值。我在这里整理了一个示例组件来说明这一点。

@Component({
    selector: 'app-list',
    templateUrl: './list.component.html',
    styleUrls: ['./list.component.css']
})
export class ListComponent {
    public Result[] Items;


    constructor(private myService: MyService) {

this.formControl.valueChanges.pipe( switchMap(值=> myService.getResults(值)) ).subscribe(结果=> this.Items =结果); } }

在此示例中,为了进行测试,我将从内部调用getResults(),然后进行测试以确保填充了Items。由于不能保证此操作会立即发生,但是subscribe逻辑完全在组件中,因此我应该如何等待以确保在检查{的值时不会收到undefined {1}}?

编辑:这是到目前为止我对测试的看法。请注意,我已经更新了上面代码中的注释,表明由于FormControl值的更改而不是单击按钮,因此是下面的Items,因此可观察对象已被订阅。

detectChanges

2 个答案:

答案 0 :(得分:0)

您必须在测试中实现request方法,以获取结果和状态,重点是使用status来确保您的api工作正常,也可以使用{{1} }以获得回应。

timeout

答案 1 :(得分:0)

这取决于您如何嘲笑myService.getResults()。如果返回of(<IResult[]>)(应该是哪个IMO),则订阅将同步运行,因此将立即运行。

it('should set items on click', () => {
  // click on the element and make sure pullResults() gets called.
  // here we will call it directly
  // Make sure you are mocking myService.getResults() to return an observable in the form 
  // of `of([...])`
  component.pullResults();
  // go ahead and make the assertion right away
  expect(component.Items).toEqual(myTestItems);
});
相关问题