间谍调用方法的实际实现



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

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

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

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

BoardSharedService.spec.ts

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();
});
});

和板共享服务.ts

@Injectable()
export class BoardSharedService {
constructor(private utilService: UtilService) { }
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
} 
}
}
}

我收到以下错误

BoardSharedService should fetch data
Expected 1 to be 7.
Error: Expected 1 to be 7.

需要帮助。!

谢谢

您需要在提供程序中提供jasminespyObjUtilService

然后你可以.and.returnValue(some_value)UtilService的方法。

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();
});

最新更新