簡體   English   中英

如何在Observable中設置NgForm值並測試其設置?

[英]How to set NgForm value in Observable and test that it was set?

我正在嘗試測試NgForm並檢查更新商店狀態時是否設置了表單的值。

@ViewChild('form') form: NgForm;

ngOnInit() {
this.subscription = this.store.select('shoppingList').subscribe(data => {
    this.editedItem = data.editedIngredient;
    this.form.setValue({ 
      name: this.editedItem.name,
      amount: this.editedItem.amount
    })
});

}

但是當設置值時

There are no form controls registered with this group yet.  
If you're using ngModel, you may want to check next tick (e.g. use setTimeout).

還嘗試創建假表格並設置它而不是NgForm

TestBed.createComponent(ShoppingEditComponent).debugElement.componentInstance.form = { value: {}, setValue: (newValue) => { this.value = newValue }};

但是在測試中它的值永遠不會更新,得到空value對象。

測試這種情況的最佳方法是什么?

@ViewChild('form')形式:NgForm;

在ngOnInit生命周期掛鈎中將不可用。

首先,您需要在構造函數或ngOnInit中創建一個表單。

只有這樣,您才能在現有表單上執行方法。

export class MyComponent {
  form: FormGroup;
  editedItem;

  constructor(
    private formBuilder: FormBuilder
  ) {}

  ngOnInit() {
    this.createForm();
    this.subscribeToShoppingList();
  }

  private createForm() {
    this.form = this.formBuilder.group({
      name: null,
      amount: null
    });
  }

  private subscribeToShoppingList() {
    this.store.select('shoppingList').subscribe(data => {
      this.editedItem = data.editedIngredient;
      this.form.setValue({ 
        name: this.editedItem.name,
        amount: this.editedItem.amount
      });
    });
  }
}

在這種情況下,您無需測試Store返回的商品,就足以對以下內容進行單元測試:

const mocks = {
  store: {
    select: sinon.stub().withArgs('shoppingList').returns(new Subject())
  }
};

let component: MyComponent;

describe('MyComponent', () => {
  beforeEach(() => {
    component = new MyComponent(
      new FormBuilder(),
      <any> mocks.store
    );
  });

  describe('ngOnInit', () => {
    beforeEach(() => {
      component.ngOnInit();
    });

    it('should create form', () => {
      expect(component.form).to.be.instanceof(FormGroup);
    });

    it('should create form with correct fields', () => {
      expect(component.form.value).to.haveOwnProperty('name');
      expect(component.form.value).to.haveOwnProperty('amount');
    });

    it('should subscribe to store.shoppingList', () => {
      expect(component.store.select).to.be.calledOnce.and.calledWith('shoppingList');
    });

    it('should set correct data from store to component', () => {
      component.store.select.next({
        editedIngredient: {
          name: 'new',
          amount: 100
        }
      });

      expect(component.editedItem.amount.to.eql(100));

      expect(component.form.value.name).to.eql('new');
    });

  });
});

我沒有測試過代碼,可能有問題,但是我希望我已經解釋了主要思想。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM