使用Angular2中的Karma启用按钮时的单元测试 [英] Unit test when a button is enabled using Karma in Angular2

查看:83
本文介绍了使用Angular2中的Karma启用按钮时的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用angular CLI的Angular2项目设置.我正在尝试测试表单组件.它具有两个字段:电子邮件和密码.两者都是required.有一个submit类型的登录按钮.只有在用户在两个字段中都提供了有效输入后,该功能才启用.

I have an Angular2 project setup using angular CLI. I'm trying to test a form component. It has two fields: email and password. Both are required. There's a login button of the type submit. It's enabled only after the user has provided valid inputs in both the fields.

<form (ngSubmit)="login()" #loginForm="ngForm">

        <md-input-container class="md-block">
            <input md-input [(ngModel)]="user.email" class="userEmail"
                name="userEmail" type="email" placeholder="Email" 
                ngControl="userEmail" 
            required>
        </md-input-container>
        <br>

        <md-input-container class="md-block">
            <input md-input [(ngModel)]="user.password" class="userPassword"
                name="userPassword" type="password" placeholder="Password" 
                ngControl="userPassword" 
            required>
        </md-input-container>
        <br>



        <!--the button is enabled only after all form fields are valid-->
        <button  color="primary" md-button 
            type="submit" class='loginButton'
        [disabled]="!loginForm.form.valid">
            Login
         </button>

现在,我想使用业力测试按钮.我浏览了文档,并能够通过在测试和验证过程中提供随机输入来测试输入:

Now, I want to test the button using karma. I went through the docs and was able to test the input, by giving a random input during testing and verifying it:

//imports...

describe('LoginComponent (inline template)', () => {
  let comp:    LoginComponent;
  let fixture: ComponentFixture<TmLoginComponent>;
  let userEmail: HTMLInputElement;
  let userPassword: HTMLInputElement;
  let loginBtn: HTMLElement;
  let title: HTMLElement;



  beforeEach(() => {

    TestBed.configureTestingModule({
      declarations: [ LoginComponent ], // declare the test component
      imports: [ MaterialModule.forRoot(), FormsModule, 
                  RouterTestingModule.withRoutes(
                  [{path: 'login', component: LoginComponent}, ])
                ],
      providers: [{provide: UserAuthenticationService, useValue: uaServiceStub }, CookieService],

    });

    fixture = TestBed.createComponent(LoginComponent);

    comp = fixture.componentInstance; //LoginComponent test instance

    // query by CSS element selector
    userEmail = fixture.debugElement.query(By.css('.userEmail')).nativeElement;
    userPassword = fixture.debugElement.query(By.css('.userPassword')).nativeElement;
    loginBtn = fixture.debugElement.query(By.css('.loginButton')).nativeElement;


//tests

//this test is successful
  it('should check initial input', () => {
    fixture.detectChanges();
    expect(userEmail.value).toBe('')
  });

//this test is successful
  it('should check later input', async(() => {    
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      userEmail.value = 'someValue';
      userEmail.dispatchEvent(new Event('change'));

      expect(userEmail.value).toBe('someValue');
    });

  }));

//EDITED: NEW TEST
it('should check loginBtn is disabled initially', () => {
  fixture.detectChanges();
  loginBtn =   fixture.debugElement.query(By.css('.loginButton')).nativeElement;
  fixture.whenStable().then(() => {
    expect(loginBtn.disabled).toBe(true)
   })
 });


//this test fails. "Expected true to be false"
  it('should check loginBtn is enabled after inputs check out', async(() => {
   fixture.detectChanges();
   fixture.whenStable().then(() => {
   userEmail.value = 'raj@gmail.com';//valid
   userEmail.dispatchEvent(new Event('change'));

   userPassword.value = 'asdf';//vaild
   userPassword.dispatchEvent(new Event('change'));
   fixture.detectChanges();
   expect(loginBtn.disabled).toBe(false)
  })
 }));

});

我不知道为什么测试失败.有人可以帮忙吗?

I don't see why the test fails. Can anybody help?

推荐答案

如果您查看DefaultValueAccessor源代码:

host: {'(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},

https ://github.com/angular/angular/blob/2.4.2/modules/%40angular/forms/src/directives/default_value_accessor.ts#L36

您会注意到,主要的错误是错误的事件名称.

you can notice that main your mistake is wrong event name.

您必须使用input事件而不是change

You have to use input event instead of change

it('should check loginBtn is enabled after inputs check out', async(() => {
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    userEmail.value = 'raj@gmail.com';
    userEmail.dispatchEvent(new Event('input'));

    userPassword.value = 'asdf';
    userPassword.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    expect(loginBtn.disabled).toBe(false)
  });
}));

柱塞示例

Plunker Example

这篇关于使用Angular2中的Karma启用按钮时的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆