Angular2 - 单元测试表单提交

问题描述 投票:6回答:3

我有一个简单的组件,它在form元素中包含两个输入字段。单击提交按钮,它将调用组件上的addUser函数。

组件模板如下:

<div>
  <form [formGroup]="signupForm" (submit)="addUser($event)" role="form" class="form-horizontal">
      <label>Firstname:</label>
      <input type="text" formControlName="firstName"> 
      <label>Lastname:</label>
      <input type="text" formControlName="lastName">
      <input type="submit" id="btnSubmit" class="btn btn-primary btn-lg" value="Register" />
  </form>
</div>

组件定义如下:

@Component({
  moduleId: module.id,  
  templateUrl: 'user.component.html'  
})
export class UserComponent {

  registered = false;

  constructor(
    private router: Router,
    private fb: FormBuilder,
    public authService: AuthService) {

      this.signupForm = this.fb.group({
            'firstName': ['', Validators.required],
            'lastName': ['', Validators.required]
        });        
  }

  addUser(event: any) {
      event.preventDefault();
      this.addUserInvoked = true;
      ......
      ......
      this.authService.register(this.signupForm.value)
        .subscribe(
        (res: Response) => {
            if (res.ok) {
                this.registered = true;
            }
        },
        (error: any) => {
            this.registered = false;                                
        });
  }
}

它工作正常。但是,在我的单元测试中,当我尝试测试在提交按钮上调用click时,然后调用addUser。但不幸的是,没有调用addUser函数。

以下是我的样本单元测试

class RouterStub {
  navigateByUrl(url: string) { return url; }
}


let comp: UserComponent;
let fixture: ComponentFixture<UserComponent>;

describe('UserComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ UserComponent ],
      schemas:      [NO_ERRORS_SCHEMA]
    });
  });

  compileAndCreate();
  tests();
});

function compileAndCreate() {
  beforeEach( async(() => {
    TestBed.configureTestingModule({
      providers: [        
        { provide: Router,      useClass: RouterStub },
        { provide: AuthService, useValue: authServiceStub },
        FormBuilder
      ]
    })
    .compileComponents().then(() => {
      fixture = TestBed.createComponent(UserComponent);
      comp = fixture.componentInstance;
    });
  }));
}

function tests() {
    it('should call addUser when submitted', () => { 
        const spy = spyOn(comp, 'addUser');  

        //*************below method doesn't work and it refreshes the page***************
        //let btnSubmit = fixture.debugElement.query(By.css('#btnSubmit'));
        //btnSubmit.nativeElement.click();

        let form = fixture.debugElement.query(By.css('form'));
        form.triggerEventHandler('submit', null);
        fixture.detectChanges();

        expect(comp.addUser).toHaveBeenCalled();
        expect(authServiceStub.register).toHaveBeenCalled();
        expect(comp.registered).toBeTruthy('user registered'); 
    });

}

我试过了

fixture.debugElement.query(By.css('#btnSubmit')).nativeElement.click()

fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null)

但我仍然无法调用addUser功能。我已经在SO here上看到了一个问题,但它也没有用。

unit-testing angular jasmine angular2-forms
3个回答
2
投票

我有同样的问题,我的解决方案是我必须将'FormsModule'导入到我的测试模块的配置中。

TestBed.configureTestingModule({
            imports: [FormsModule]
)}

也许这有用吗?


1
投票
  1. 你需要spyon你想要检查的功能和它依赖的功能。
  2. 分派事件后第二次调用fixture.detectChanges。
  3. 还要确保您的表单在dom上可见,否则查询将返回null

我可以这样做:

let yourService: YourService;
beforeEach(() => {
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
    store = TestBed.get(YourService);
    fixture.detectChanges();
});


it('should call the right funtion', () => {       
    spyOn(yourService, 'yourMethod');// or spyOn(component, 'yourMethod');       
    const fakeEvent = { preventDefault: () => console.log('preventDefault') };
    fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', fakeEvent);
    expect(yourService.yourMethod).toHaveBeenCalledWith(
      //your logic here
    );
});

0
投票

下面是示例代码:1:将Xcomponent替换为您的组件名称2:将formID替换为您的表单的ID。

import {async, ComponentFixture, TestBed} from '@angular/core/testing';

    import {FormsModule} from '@angular/forms';
    import {By} from '@angular/platform-browser';

    describe('Xcomponent', () => {
      let component: Xcomponent;
      let fixture: ComponentFixture<Xcomponent>;

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [FormsModule],
          declarations: [Xcomponent]
        })
          .compileComponents();
      }));

      beforeEach(() => {
        fixture = TestBed.createComponent(Xcomponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });

      it('should create', () => {
        expect(component).toBeTruthy();
      });

      it('should call save() method on form submit', () => {
        /*Get button from html*/
        fixture.detectChanges();
        const compiled = fixture.debugElement.nativeElement;
        // Supply id of your form below formID
        const getForm = fixture.debugElement.query(By.css('#formID'));
        expect(getForm.triggerEventHandler('submit', compiled)).toBeUndefined();
      });

    });
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.