【问题标题】:Angular unit test - changes are not detected on button click角度单元测试 - 单击按钮时未检测到更改
【发布时间】:2020-10-04 16:44:51
【问题描述】:

我正在测试这个在提交按钮点击时触发的方法

  addItem(): void{
    console.log("Adding Item")
    this.newItem.id= "100"
    this.newItem.name ="Shampoo"
 }

我想在单击提交按钮时从单元测试中触发此方法。但是我认为它不会触发,因为预期值 '100' 和 'Shampoo' 是 ''。所以断言失败

单元测试类



let store: MockStore<AppState>;
let fixture :ComponentFixture<AppComponent>;
let component: AppComponent;

const initialState = { 
  shopping:{
    list: [],
    loading: false,
    error: undefined
  }, 
  loggedIn: false };

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule ,
        ReactiveFormsModule,
        FormsModule    
      ],
      providers:[
        provideMockStore({ initialState }),
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents().then(()=>{

      fixture = TestBed.createComponent(AppComponent);
      component = fixture.componentInstance;
    });

  }));

  it('should create the app', () => {

    expect(component).toBeTruthy();
  });


  fit('should add item on button click', () => {

    fixture.detectChanges();
    expect(component.newItem.id).toEqual('');
    expect(component.newItem.name).toEqual('');
    //debugger;
    const btn:DebugElement =fixture.debugElement.query(By.css('#addBtn'))
    btn.triggerEventHandler('ngSubmit',null);
    expect(component.newItem.id).toEqual('100');
    expect(component.newItem.name).toEqual('Shampoo');
  });
});

这是我的 html 类

  <form (ngSubmit)="addItem()">
    <input type="text" [(ngModel)]="newItem.name" placeholder="Item" name="itemName"/>
    <button type="submit" id="addBtn">+Add</button>
  </form>

我做错了什么

【问题讨论】:

    标签: angular unit-testing


    【解决方案1】:

    把测试改成这样:

      fit('should add item on button click', async() => { // add async here because some aspects 
    // Angular forms are asynchronous
    
        fixture.detectChanges();
        expect(component.newItem.id).toEqual('');
        expect(component.newItem.name).toEqual('');
        //debugger; grab the nativeElement (HTMLElement) by adding .nativeElement towards the end of the line
        const btn = fixture.debugElement.query(By.css('#addBtn')).nativeElement;
        btn.click(); // click the button
        await fixture.whenStable(); // wait until form promises have completed, this could be not needed.
        expect(component.newItem.id).toEqual('100');
        expect(component.newItem.name).toEqual('Shampoo');
      });
    

    【讨论】:

      【解决方案2】:

      看来我必须触发表单提交,而不是按钮点击

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

      【讨论】:

        猜你喜欢
        • 2018-06-12
        • 1970-01-01
        • 2019-10-11
        • 1970-01-01
        • 2013-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多