angular - 使用 Jasmine 在 Angular 中嵌套函数测试覆盖率

标签 angular testing jasmine

我在尝试使用指令测试 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();
  });
});

提前致谢。

最佳答案

您可以像在示例中那样使用 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();
  });
});

关于angular - 使用 Jasmine 在 Angular 中嵌套函数测试覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57574709/

相关文章:

javascript - 我如何测试一个函数没有被调用?

javascript - Angular 2 Material Autocomplete - 获取(有效)所选项目

angular - 如何通过单击按钮打开 PrimeNG p 对话框并将数据从组件传递到 p 对话框?

windows - 单个 .msi Windows 程序包安装程序文件的最大大小是多少?

android - Appium:不应在启动/测试解锁密码时启动应用程序或 Activity

ruby-on-rails - Rails 单元测试是否应该命中数据库?

angular-fontawesome + FaIconLibrary + Angular + Storybook.js = :(

angular - 在 Angular4 中使用网络套接字?

jasmine - 在nodejs上使用gulp + babel + jasmine进行测试

使用 Jasmine 和 Sinon 在匿名函数中测试 Backbone 代码