【问题标题】:Nested function test coverage in Angular with JasmineJasmine 在 Angular 中的嵌套函数测试覆盖率
【发布时间】:2019-08-20 13:22:47
【问题描述】:

我在尝试使用指令测试 cookie 删除时遇到问题。

我的指令如下:

import { Directive, HostListener } from '@angular/core';
import { CookieService } from 'angular2-cookie/core';

@Directive({
  selector: '[appCloseWindow]'
})

/**
 * Directive that when we close the window, removes the cookie
 */
export class CloseWindowDirective {

  constructor( private readonly _cookieService: CookieService ) { }

  @HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event: Event) {
    const cookie = this._cookieService.get('RandomCookie');
    if ( cookie !== undefined ) {
      this._cookieService.remove('RandomCookie');
    }
  }
}

所以在测试中我的问题是我无法到达删除部分,并且不知道该怎么做。

我现在的测试是这样的,我是新来的 Jasmine 测试所以可能是错误的......

import { TestBed, async } from '@angular/core/testing';
import { CloseWindowDirective } from './close-window.directive';
import { CookieService } from 'angular2-cookie';

fdescribe('Directive: CloseWindow', () => {
  const service = new CookieService;
  const directive = new CloseWindowDirective(new CookieService);

  beforeEach(async(() => {
    spyOn(directive, 'beforeunloadHandler').and.callThrough();
    spyOn(service, 'get').and.returnValue('cookieTest');
    spyOn(service, 'remove').and.callThrough();

    TestBed.configureTestingModule({
      providers: [CookieService],
      declarations: [CloseWindowDirective]
    })
      .compileComponents();
  }));

  it('should create an instance', () => {
    expect(directive).toBeTruthy();
  });

  it('should call directive method', () => {
    directive.beforeunloadHandler(new Event('beforeunload'));
    expect(directive.beforeunloadHandler).toHaveBeenCalled();
  });

  it('should call remove the cookie', () => {
    const cookie = service.get('testCookie');
    service.remove(cookie);
    expect(service.remove).toHaveBeenCalled();
  });
});

提前致谢。

【问题讨论】:

    标签: angular testing jasmine


    【解决方案1】:

    您可以像在示例中那样使用spyOn,因此get 方法将返回一个cookie,并调用remove 方法。

    @Component({
      template: '<div appCloseWindow></div>'
    })
    class TestComponent {}
    
    function setup(): {
      directive: CloseWindowDirective,
      service: jasmine.SpyObj<CookieService>
    } {
       TestBed.configureTestingModule({
        providers: [CookieService],
        declarations: [TestComponent, CloseWindowDirective]
      });
    
      const componentFixture = TestBed.createComponent(TestComponent);
      const directiveElement = componentFixture.debugElement.query(By.directive(CloseWindowDirective));
      const directive = directiveElement.injector.get<CloseWindowDirective>(CloseWindowDirective)
    
      return {
        directive: directive,
        service: TestBed.get(CookieService)
      };
    }
    
    describe(CloseWindowDirective.name, () => {
      it('should call remove the cookie', () => {
        const { service } = setup();
    
        spyOn(service, "get").and.returnValue("cookieTest");
        const removeSpy = spyOn(service, "remove").and.callThrough();
    
        window.dispatchEvent(new Event("beforeunload"))
        expect(removeSpy).toHaveBeenCalled();
      });
    });
    

    或者你可以模拟整个服务对象,比如:

    ...
    
    function setup(): {
      const service = jasmine.createSpyObj<CookieService>(CookieService.name, [
          "get",
          "remove"
      ]);
    
      TestBed.configureTestingModule({
        declarations: [TestComponent, CloseWindowDirective],.
        providers: [
            { provide: CookieService, useValue: service }
        ]
      });
    
      ...
    
      return {
        directive: directive,
        service: service
      };
    }
    
    describe(CloseWindowDirective.name, () => {
      it('should call remove the cookie', () => {
        const { service } = setup();
        service.get.and.returnValue("cookieTest");
    
        window.dispatchEvent(new Event("beforeunload"));
        expect(service.remove).toHaveBeenCalled();
      });
    });
    

    【讨论】:

    • 谢谢你的回答,我马上去试试。
    • @Arm144 如果您有任何问题,请随时问我。
    猜你喜欢
    • 2016-07-09
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2019-12-26
    相关资源
    最近更新 更多