【问题标题】:How to run a Karma jasmine test that runs the focus() - method of an HTMLElement in the background?如何运行在后台运行 focus() - HTMLElement 方法的 Karma jasmine 测试?
【发布时间】:2019-09-07 17:24:56
【问题描述】:

目标

我想测试一个处理编辑器及其输入的组件。 该组件有一个 FormControl 和一个 FocusMonitor。 仅当组件私有焦点字段设置为 true 时,才应更新特定值。 FocusMonitor 更新组件的私有焦点字段。

我使用 Karma Jasmine 4.0.1 运行测试。

问题:

当我选择(聚焦)运行测试的 ChromeBrowser 时,测试成功。 如果我只是通过终端输入开始测试并让它在后台运行 - 同时处理其他事情 - 测试失败。

失败的发生是因为当我没有主动选择正在运行的测试浏览器的窗口时,FocusMonitor Observable 不发出一个事件。

代码

组件内部

focusMonitor.monitor(elementRef.nativeElement, true).subscribe(origin => {
            this.focused = !!origin;
            this.someUpdateAlgorithm();
        });


//somewhere inside the component. This ward keeps off unwanted changes via the model.

if (!this.focused) {
    return;
}



component.spec 内部

fit('should change value of input control', () => {
            fixture.debugElement.query(By.css('input')).nativeElement.focus();
            model.setValue(3);
            const inputText = getCurrentDisplayValue();
            expect(inputText).toBe('3');
        });

结果

预期结果:

案例:主动选择运行测试浏览器(Chrome)的窗口

expect(inputText).toBe('3'); //成功输入文本 === '3'

案例:运行测试浏览器(Chrome)最小化(在后台)

expect(inputText).toBe('3'); //成功输入文本 === '3'

实际结果:

案例:主动选择运行测试浏览器(Chrome)的窗口

expect(inputText).toBe('3'); //成功输入文本 === '3'

案例:运行测试浏览器(Chrome)最小化(在后台)

expect(inputText).toBe('3'); //失败的输入文本 === ''

【问题讨论】:

    标签: angular testing jasmine focus background-process


    【解决方案1】:

    要使您的测试独立于环境,您可以模拟FocusMonitor

    describe('YourComponent', () => {
      let focusMonitorObservable: Subject<string>;
    
      beforeEach(async(() => {
        const fmSpy = jasmine.createSpyObj('FocusMonitor', ['monitor']);
        TestBed.configureTestingModule({
          // ...
          providers: [
            { provide: FocusMonitor, useValue: fmSpy },
          ]
        })
        .compileComponents();
        focusMonitorSpy = TestBed.get(FocusMonitor);
        focusMonitorObservable = new Subject<string>();
        focusMonitorSpy.monitor.and.returnValue(focusMonitorObservable);
      }));
    
      it('should change value of input control', () => {
        focusMonitorObservable.next('mouse'); // emulating the focus change
        model.setValue(3);
        const inputText = getCurrentDisplayValue();
        expect(inputText).toBe('3');
      });
    });
    
    

    【讨论】:

    • 谢谢您的回答。如果它符合我的需要,我会试一试并回复:-)
    猜你喜欢
    • 2018-10-04
    • 2019-02-17
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多