为angular 9编写测试用例--google analytics events。

问题描述 投票:0回答:1

我怎么能在jasmin karma上为下面的代码写测试用例呢,我甚至不知道从哪里开始写下面的测试用例emitEventcan anyone help me out so I can have clear picture how the things goes on the road...

import { Injectable } from '@angular/core';

@Injectable()
export class GaEventsService {
  public emitEvent(
    eventLabel: string = null,
    eventCategory: string,
    eventAction: string,
    eventValue: number = null
  ) {
    (window as any).ga('send', 'event', {
      eventLabel,
      eventCategory,
      eventAction,
      eventValue,
    });
  }
}

这是我的测试用例规格.ts

import { TestBed } from '@angular/core/testing';
import { GaEventsService } from './ga-events.service';

fdescribe('DateFormatService', () => {
  let service: GaEventsService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        GaEventsService,
        // { provide: GaEventsService, useClass: GaEventsServiceMock },
      ],
    });
    service = TestBed.inject(GaEventsService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  beforeAll(() => {
    // (<any>window).gtag=function() {} // if using gtag
    (window as any).ga = () => {};
  });

  it('should be created service', () => {
    expect(GaEventsService).toBeDefined();
  });

  it('should do something...', () => {
    const gaSpy = spyOn(service.emitEvent, 'ga');
    expect(gaSpy).toHaveBeenCalledWith('send', 'event', {
      eventLabel: 'eventLabel',
      eventCategory: 'eventCategory',
      eventAction: 'eventAction',
      eventValue: 'eventValue',
    });
  });
});

这里是未覆盖的行,我想所有的--。代码覆盖图

angular typescript unit-testing jasmine karma-jasmine
1个回答
0
投票

阅读测试服务的文档 此处

试试这段代码。

it('should do something...', () => {
    // insert here initialisation for variables eventLabel, eventCategory, eventAction, eventValue with appropriate values
    const gaSpy = spyOn((window as any), 'ga');
    service.emitEvent(eventLabel, eventCategory, eventAction, eventValue);
    expect(gaSpy).toHaveBeenCalledWith('send', 'event', {
      eventLabel,
      eventCategory,
      eventAction,
      eventValue,
    });
  });

0
投票
it('should do something...', () => {
    // insert here initialisation for variables eventLabel, eventCategory, eventAction, eventValue with appropriate values
    const gaSpy = spyOn(window as any, 'ga');
    service.emitEvent('eventLabel', 'eventCategory', 'eventAction', 1);
    expect(gaSpy).toHaveBeenCalledWith('send', 'event', {
      eventLabel: 'eventLabel',
      eventCategory: 'eventCategory',
      eventAction: 'eventAction',
      eventValue: 1,
    });
  });

是的,上面的代码是有效的,但我还是很好奇为什么它没有100%覆盖语句和分支 @orlyohreally不包括的发言----形象

© www.soinside.com 2019 - 2024. All rights reserved.