SpyOn调用方法

时间:2018-05-10 11:43:33

标签: angular unit-testing karma-jasmine

我正在尝试为角度应用程序编写单元测试测试用例,并且我使用SpyOn()方法来监视服务方法。

我正在测试一个名为getCurrentBoardTimeIdByCurrentTime()的方法的服务,该方法在内部调用另一个名为
的服务方法 utilService.getHour()utilService.getWeekday()

我在这两种方法中使用了间谍,并分别返回了25,之后getCurrentBoardTimeIdByCurrentTime()必须返回7

现在,当我调用服务方法getCurrentBoardTimeIdByCurrentTime()时,不会使用spy的返回值,而是调用实际的函数本身,导致测试失败。

BoardSharedService.spec.ts

import { TestBed, inject } from '@angular/core/testing';
import { BoardSharedService } from './board-shared.service';
import { UtilService } from './../shared/util.service';
import { extend } from 'webdriver-js-extender';

describe('BoardSharedService', () => {
  let service: BoardSharedService;
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        BoardSharedService,
        UtilService
      ]
    });
  });

  it('should fetch data', () => {
    service = TestBed.get(BoardSharedService);
    const getHourSpy = jasmine.createSpyObj('UtilService', ['getHour']);
    const getWeekDaySpy = jasmine.createSpyObj('UtilService', ['getWeekDay']);

    getHourSpy.getHour.and.returnValue(2);
    getWeekDaySpy.getWeekDay.and.returnValue(5);

    expect(service.getCurrentBoardTimeIdByCurrentTime()).toBe(7);
    expect(service.getCurrentBoardTimeIdByCurrentTime).toHaveBeenCalled();
  });

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

和boardSharedService.ts

import { Injectable } from '@angular/core';
import { UtilService } from './util.service';
import { Day } from './day.enum'
@Injectable()
export class BoardSharedService {

  constructor(private utilService: UtilService) { }

  /**
   * AM = 1
   * PM = 2
   * Weekend AM = 3
   * Friday AM = 4
   * Monday AM = 5
   * Weekend PM = 6
   * Friday PM = 7
  */
  getCurrentBoardTimeIdByCurrentTime() {
    const currentHour = this.utilService.getHour();
    const currentDay = this.utilService.getWeekDay();
    if (currentHour < 6 || currentHour > 17) {
      // PM
      if (currentDay === Day.Friday) {
        return 7; // Friday PM
      } else if (currentDay === Day.Sunday || currentDay === Day.Saturday) {
        return 6; // Weekend PM
      }
      return 2; // PM
    } else {
      // AM
      if (currentDay === Day.Monday) {
        return 5; // Monday AM
      } else if (currentDay === Day.Friday) {
        return 4; // Friday AM
      } else if (currentDay === Day.Sunday || currentDay === Day.Saturday) {
        return 3; // Weekend AM
      }
      return 1; // AM
    }
  }
}

我收到以下错误

BoardSharedService should fetch data
Expected 1 to be 7.
Error: Expected 1 to be 7.
at stack (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1640:17)
at buildExpectationResult (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1610:14)
at Spec.expectationResultFactory (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:655:18)
at Spec.addExpectationResult (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:342:34)
at Expectation.addExpectationResult (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:599:21)
at Expectation.toBe (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1564:12)
at Object.<anonymous> (http://localhost:9876/_karma_webpack_/main.bundle.js:33942:62)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/polyfills.bundle.js:6179:26)
at ProxyZoneSpec.webpackJsonp.../../../../zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/vendor.bundle.js:145061:39)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/polyfills.bundle.js:6178:32)
Error: <toHaveBeenCalled> : Expected a spy, but got Function.
Usage: expect(<spyObj>).toHaveBeenCalled()
Error: <toHaveBeenCalled> : Expected a spy, but got Function.
Usage: expect(<spyObj>).toHaveBeenCalled()
at compare (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:3273:17)
at Expectation.toHaveBeenCalled (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1543:35)
at Object.<anonymous> (http://localhost:9876/_karma_webpack_/main.bundle.js:33943:60)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/polyfills.bundle.js:6179:26)
at ProxyZoneSpec.webpackJsonp.../../../../zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/vendor.bundle.js:145061:39)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/polyfills.bundle.js:6178:32)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run (http://localhost:9876/_karma_webpack_/polyfills.bundle.js:5929:43)
at runInTestZone (http://localhost:9876/_karma_webpack_/vendor.bundle.js:144632:34)
at Object.<anonymous> (http://localhost:9876/_karma_webpack_/vendor.bundle.js:144647:20)
at attemptSync (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1950:24)

需要帮助。!

谢谢

1 个答案:

答案 0 :(得分:2)

您需要在jasmine的提供商中提供spyObj UtilService

然后您可以.and.returnValue(some_value) UtilService的方法{。}}。{/ 1>

providers: [
        BoardSharedService,
        {provide : UtilService, useValue: jasmine.createSpyObj('UtilService', ['getHour', 'getWeekDay']);
      ]

在规范中你可以做这样的事情

  it('should fetch data', () => {
    // UPDATE: You are doinf expect(service.getCurrentBoardTimeIdByCurrentTime).toHaveBeenCalled();
    // And you have not spy'd on service.getCurrentBoardTimeIdByCurrentTime method, it will throw error.
    jasmine.spyOn(service, 'getCurrentBoardTimeIdByCurrentTime').and.callThrough();
    service = TestBed.get(BoardSharedService);

    let utilService= TestBed.get(UtilService);

    utilService.getHour.and.returnValue(2);
    utilService.getWeekDay.and.returnValue(5);

    expect(service.getCurrentBoardTimeIdByCurrentTime()).toBe(7);
    expect(service.getCurrentBoardTimeIdByCurrentTime).toHaveBeenCalled();
  });