响应式表单测试

响应式表单提供了相对简单的测试策略,因为它们能提供对表单和数据模型的同步访问,而且不必渲染 UI 就能测试它们。在这些测试中,控件和数据是通过控件进行查询和操纵的,不需要和变更检测周期打交道。

视图到模型

  1. it('should update the value of the input field', () => {
  2. const input = fixture.nativeElement.querySelector('input');
  3. const event = createNewEvent('input');
  4. input.value = 'Red';
  5. input.dispatchEvent(event);
  6. expect(fixture.componentInstance.favoriteColorControl.value).toEqual('Red');
  7. });

模型到视图

  1. it('should update the value in the control', () => {
  2. component.favoriteColorControl.setValue('Blue');
  3. const input = fixture.nativeElement.querySelector('input');
  4. expect(input.value).toBe('Blue');
  5. });