【问题标题】:How to write unit tests for Angular Flex-layout directives (fxHide, fxShow)?如何为 Angular Flex 布局指令(fxHide、fxShow)编写单元测试?
【发布时间】:2021-03-12 04:47:17
【问题描述】:

我认为 Angular Flex-Layout 库很棒,但我不知道如何测试它的指令,如 fxHide 或 fxShow ???? 例如,如果您有这样的模板:

<div fxHide.lt-md class="my-div">Should not be visible for small devices (xs, sm)</div>

你应该如何模拟屏幕尺寸值来测试它?

【问题讨论】:

    标签: angular unit-testing jasmine angular-flex-layout


    【解决方案1】:

    所以我在@angular/flex-layout 内部单元测试here 中找到了答案。

    要模拟这些值,您必须像这样注入 MatchMedia 的模拟版本:

    import {
      FlexLayoutModule,
      ɵMatchMedia as MatchMedia,
      ɵMockMatchMedia as MockMatchMedia,
    } from '@angular/flex-layout';
    
    describe('template tests', () => {
      let mediaController: MockMatchMedia;
    
      let fixture: ComponentFixture<MyComponent>;
      let component: MyComponent;
      let el: DebugElement;
    
      beforeEach(
        waitForAsync(() => {
          TestBed.configureTestingModule({
            imports: [FlexLayoutModule],
            providers: [{ provide: MatchMedia, useClass: MockMatchMedia }],
            declarations: [MyComponent],
          })
            .compileComponents()
            .then(() => {
              fixture = TestBed.createComponent(MyComponent);
    
              inject([MatchMedia], (_matchMedia: MockMatchMedia) => {
                mediaController = _matchMedia;
              })();
    
              component = fixture.componentInstance;
              el = fixture.debugElement;
            });
        }),
      );
    
      afterEach(() => {
        mediaController.clearAll();
      });
    
      it('should not display day of week for mobile', () => {
        mediaController.activate('lt-md');
        fixture.detectChanges();
        const divDbEl = el.query(By.css('.my-div'));
        expect(divDbEl).toBeTruthy();
        expect(divDbEl.styles.display).toEqual('none'); // Should be hidden
      });
    });
    

    所以,你需要:

    1. 从@angular/flex-layout/core 导入模拟:import { ɵMatchMedia as MatchMedia, ɵMockMatchMedia as MockMatchMedia } from '@angular/flex-layout/core';
    2. 声明let mediaController: MockMatchMedia;
    3. 在 beforeEach 里面配置测试模块:
    imports: [FlexLayoutModule],
    providers: [{ provide: MatchMedia, useClass: MockMatchMedia }]
    
    1. 编译组件后,注入 MatchMedia 的模拟版本:
    inject([MatchMedia], (_matchMedia: MockMatchMedia) => {
            mediaController = _matchMedia;
    })();
    
    1. 在 afterEach 里面你可以重置一些值:
        afterEach(() => {
            mediaController.clearAll();
        });
    
    1. 激活你需要的屏幕尺寸:mediaController.activate('lt-md');
    2. 测试显示样式是否设置为“无”:expect(divDbEl.styles['display']).toEqual('none');

    ???

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 2015-02-16
      • 1970-01-01
      • 2020-02-17
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多