使用ngModel进行角度2单元测试

时间:2016-10-25 05:42:06

标签: javascript unit-testing angular angular-cli

我正在使用角度为2.1的最新角度cli。 我想编写的组件测试很简单:从服务中获取一些数据并显示它。

当数据仅显示在段落中时,它可以正常工作,但当它绑定到textarea时,它不会显示。

以下是我的模板的摘录:

<p *ngIf="!isBusy" class="twain"><i>{{settings.blockLoginMessage}}</i></p> <textarea id="blockLoginMessage" name="blockLoginMessage" [(ngModel)]="settings.blockLoginMessage" class="form-control"></textarea>

和相应的测试:

describe('SettingsComponent', () => {

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [SharedModule, TranslateModule.forRoot()],
        declarations: [SettingsComponent],
        providers: [
            Overlay,
            ToastsManager,
            ViewContainerRef,
            TranslateService,
            SettingsService
        ]
    });

    fixture = TestBed.createComponent(SettingsComponent);
    comp = fixture.componentInstance;

    settingsService = fixture.debugElement.injector.get(SettingsService);

    getSettingsSpy = spyOn(settingsService, 'getSettings')
        .and.returnValue(Observable.of(new Settings(true, false, 'test')).delay(500).toPromise());

    setSettingsSpy = spyOn(settingsService, 'setSettings')
        .and.returnValue(Observable.of(true).delay(500));

    fixture.detectChanges(); 
});

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

it('should show busy indicator as long as there are no settings', () => {
    let busyPanel = fixture.debugElement.query(By.css('#busyPanel'));
    expect(busyPanel).not.toBeNull('cant find busy');
});

it('should show loaded settings after observable finished (done)', done => {
    fixture.detectChanges();

    // get the spy promise and wait for it to resolve
    getSettingsSpy.calls.mostRecent().returnValue.then(() => {
        fixture.detectChanges();

        let de = fixture.debugElement.query(By.css('.twain'));
        let el = de.nativeElement;

        expect(el.textContent).toBe('test', 'show loaded settings');

        let de2 = fixture.debugElement.query(By.css('#blockLoginMessage'));
        let el2: HTMLTextAreaElement = de2.nativeElement;

        expect(el2.textContent).toBe('test', 'show loaded settings');

        done();
    });
});

});

有没有人提示为什么这不起作用? 此外,我的异步和伪同步尝试完全失败,当我的承诺延迟时,如上所述

1 个答案:

答案 0 :(得分:5)

自RC5以来,

ngModel异步更新。你应该以异步方式测试它:

it('should check initial value of ngModel', async(() => {
  let fixture = TestBed.createComponent(TestComponent);
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    let el = fixture.debugElement.query(By.css('select your input'));
    let actual = selectElement.nativeElement.value;
    expect(expected).toBe(actual);
  });
}));