3

我有一个简单的应用程序,有 1 个输入:

@Component({   selector: 'mycomponent',   styles: [

  ],   template: `
    <div class="new-stuff">
      <div>
        <div>
        Name: <input type="text" class="new-stuff-name" [(ngModel)]="stuff.name"/>
        </div>
        <div class="new-stuff-name-error" *ngIf="nameError != null">
          {{nameError}}
        </div>
      </div>

      <button class="new-stuff-save" (click)="checkStuff()">Add idea</button>
    </div>  `, }) 
export class StuffComponent implements OnInit {
   public stuff = {name: ''};
   public allStuff = [];
   public checkStuff() {
    if (this.stuff.name.length === 0) {
      this.nameError = 'The name field cannot be empty';
    }

    if (this.stuff.name.length > 0) {
      this.allStuff.push(this.stuff);
      this.stuff= { name: ''};
    }
  }
 }

当我运行应用程序时,我看到值发生变化,一切看起来都捆绑在一起,但是当我尝试测试时,当我更改输入框中的值并单击按钮时,不会显示错误消息,因为仍然显示错误消息,因为输入值不变。

这是我的茉莉花测试:

describe(`stuff`, () => {
  let comp: StuffComponent ;
  let fixture: ComponentFixture<StuffComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [StuffComponent ],
      schemas: [NO_ERRORS_SCHEMA],
      imports: [FormsModule],
    }).compileComponents();
    fixture = TestBed.createComponent(StuffComponent );
    comp = fixture.componentInstance;
  }));

  describe('adding a new stuff', () => {
    let stuffNameInput;
    let saveButton;
    beforeEach(() => {
      stuffNameInput = fixture.nativeElement
        .querySelectorAll('.new-stuff-name')[0];
      saveButton = fixture.debugElement.nativeElement.querySelector(
        '.new-stuff-save');
    });

    describe('when is successfull', () => {
      beforeEach(async(() => {
        stuffNameInput.value = 'New Stuff';
        stuffNameInput.dispatchEvent(new Event('input'));
        saveButton.click();
        fixture.detectChanges();
      }));
      it('should display an error', () => {
        let errorDiv = fixture.nativeElement
          .querySelectorAll('.new-stuff-desc-error');
        expect(errorDiv.length)
          .toBe(0, 'Error message displayed');
      });
    });
  });
});

我尝试了多种方法,将 async 替换为 fakeAsync,调用 tick 函数,将 click 移动到 fixture.whenStable().then 块内,将 div 的检查移动到 fixture.whenStable().then 块。到目前为止没有任何效果。

我正在使用4.1.3角度版本

4

2 回答 2

1

回答我自己的问题以记录问题。

使用 stuff.name 作为 ngModel 效果不是很好。

我将 stuff.name 更改为 name 并开始工作

于 2017-05-26T17:31:57.577 回答
0

在我的测试中,我发现 mousedown 比 click() 效果更好:

    const e: Event = document.createEvent('HTMLEvents');
    e.initEvent('mousedown', false, true);
    itemElements[1].nativeElement.dispatchEvent(e);
于 2017-05-25T21:41:55.600 回答