角度测试在被动形式上提交事件

Bla*_*axy 4 jasmine typescript karma-runner karma-jasmine angular

上下文

我有一个基本形式的组件(反应形式).我尝试在此表单上测试提交事件,看它是否正确调用了必要的方法.

我的问题

我无法触发表单的提交事件

Component.html

<form class="form-horizontal"
  id="staticForm"
  [formGroup]="mySimpleForm"
  (ngSubmit)="sendMethod();"
>
  <input type="text" formGroupName="email">
  <button type="submit">Send form</button>
</form>
Run Code Online (Sandbox Code Playgroud)

Component.ts

  ngOnInit() {
    this.initSimpleForm();
  }

  private initSimpleForm() {
    let file = null;

    this.mySimpleForm = this.formBuilder.group({
      email: [
        '',
        [
          Validators.required
        ]
      ]
    });
  }

  sendMethod() {
    console.log('submitted');
  }
Run Code Online (Sandbox Code Playgroud)

component.spec.ts

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MyComponent
      ],
      imports: [],
      providers: [
        FormBuilder
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    comp = fixture.componentInstance;
});  

it(`should notify in console on form submit`, () => {
    spyOn(console, 'log');

    comp.mySimpleForm.controls['email'].setValue('test@test.com');
    fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null);     
    fixture.detectChanges();

    expect(console.log).toHaveBeenCalled(); // FAILS
});

// TO make sure my spy on console log works, I made this and it works

it(`will notify on direct sendMethod Call`, () => {
    spyOn(console, 'log');

    comp.sendMethod();      
    fixture.detectChanges();

    expect(console.log).toHaveBeenCalled(); // SUCCESS
});
Run Code Online (Sandbox Code Playgroud)

我也尝试过而不是submit在表单上调用:

fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
Run Code Online (Sandbox Code Playgroud)

然后如何触发表单提交事件?

yur*_*zui 7

第一个选项是ngSubmit直接调用:

.triggerEventHandler('ngSubmit', null); 
Run Code Online (Sandbox Code Playgroud)

第二个选项是导入ReactiveFormsModule,它将submit在表单内部设置处理程序.所以你的触发方法应该工作:

TestBed.configureTestingModule({
      declarations: [
        MyComponent
      ],
      imports: [ReactiveFormsModule], // <== import it
      providers: []
Run Code Online (Sandbox Code Playgroud)

  • 它不起作用,因为没有提交事件的处理程序,因为没有指令可以处理它因为你没有导入包含这个指令的ReactiveFormsModule (2认同)