首页 > 解决方案 > 单元测试自定义指令

问题描述

我正在使用材料角度,并且我有一个带有 mat-checkbox 的表格。

复选框上方有使用条款,用户必须将使用条款滚动到底部才能启用默认禁用的 mat-checkbox。

问题是使用 [disabled] 指令发送消息(使用指令必须在 ts blablabla 中使用是不好的)。

我的解决方案是创建专用指令:

export class MyDisabledDirective {
 @Input() set myDisabled(condition: boolean) {
    const input = this.ngControl.control;
    condition ? input.disable() : input.enable();
  }

  constructor( private ngControl: NgControl ) {
  }
}

好的,很简单,它有效。

现在我需要对该指令进行单元测试,但这就像不可能,我尝试的任何东西都不起作用。

现在规格看起来像:

@Component({
  selector: fake-component',
  template: `
    <button [myDisabled]="condition">Testing</button>
  `,
})
class FakeComponent {
  condition = true;
}

describe('DisabledDirective', () => {
  let component: FakeComponent;
  let fixture: ComponentFixture<FakeComponent>;
  let button: DebugElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [FakeComponent, MyDisabledDirective],
      providers: [NgControl],
    });
    fixture = TestBed.createComponent(FakeComponent);
    component = fixture.componentInstance;
    button = fixture.debugElement.query(By.css('button'));
  });

  it('should disable if the condition is true', () => {
    component.condition = true;
    expect(button.nativeElement.disabled).toBeTruthy();
  });

  it('should enable if the condition is false', () => {
    component.condition = true;
    expect(button.nativeElement.disabled).toBeFalsy();
  });
});

它不起作用,并且button.nativeElement.disabled每次都是假的。我想知道我尝试进行测试的方式是否良好。

希望你能帮助我,问候

控制台日志: 在此处输入图像描述

标签: angularunit-testingkarma-jasmine

解决方案


推荐阅读