Angular6测试:“ By.css”调用未捕获按钮

时间:2019-03-27 19:36:17

标签: angular button jasmine karma-runner

我有一个下面的HTML,我想在其中测试提交按钮事件。我添加了一个ID,类名等并尝试运行。仍然失败。

 <div *ngIf = 'reportParams' style="width:90%">
  <form (ngSubmit)="onSubmit()" [formGroup]="form"  target="_blank"  method="POST" > 
    <div align ="center">
      <span>
            <button mat-raised-button formControlName = "submitButtonControl" class="submitButtonControl"
            name="submitButtonControl" id = 'submitButtonControl' ngDefaultControl [disabled]="!form.valid" type = 'Submit' color='primary'  >
              {{generateButton}}
            </button>&nbsp;&nbsp;&nbsp;
        <button mat-raised-button (click)="resetButtonClick()" type="reset"  >
          Reset
        </button>
      </span>
    </div>
  </form>
</div>

下面是我试图捕获事件但重用null的spec.ts。

describe('ReportingFormComponent', () => {
  let component: ReportingFormComponent;
  let fixture: ComponentFixture<ReportingFormComponent>;
  let debugElement: DebugElement;
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [ReportingFormComponent],
    });
    fixture = TestBed.createComponent(ReportingFormComponent);
    component = fixture.componentInstance;
  describe('onSubmit', () => {
    it('makes expected calls', () => {
      const value = {}

    let submitButton = 
      fixture.debugElement.query(By.css('#submitButtonControl')); 
      console.log(submitButton);    //capturing null
    });
  });
});

我在fixture.debugElement.query(By.css('#submitButtonControl'));通话中错过了什么吗?我看到的所有示例都使用相同的示例。我想念什么?

1 个答案:

答案 0 :(得分:0)

设置测试床后,检测变化:

beforeEach(async(() => {

TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [ReportingFormComponent],
    }).compileComponents();
}));

beforeEach(() => {    
        fixture = TestBed.createComponent(ReportingFormComponent);
        component = fixture.componentInstance;
        fixture.detectChanges(); // this is what you need
    });