将 jasmie .toHaveBeenCalledWith() 函数与 Moment 对象一起使用
Using jasmie .toHaveBeenCalledWith() function with Moment Objects
我在 angular (4) -
中进行了以下测试
it('should call service',
async(inject([CommentTableComponent], (cmp: CommentTableComponent) => {
spyOn(mockSock, 'getComments').and.callThrough();
cmp.ngOnInit();
expect(mockSock.getComments).toHaveBeenCalledWith('api/jobs/604', moment());
})));
抛出错误:
Expected spy getComments to have been called with [ 'api/jobs/604', Sat Apr 29 2017 12:31:07 GMT+0100 ] but actual calls were [ 'api/jobs/604', Sat Apr 29 2017 00:00:00 GMT+0100, Sat Apr 29 2017 12:31:07 GMT+0100 ].
因为这些字符串显然是相同的,我假设这是因为 now 的测试值比组件 运行 时的值晚了几毫秒,并且这些毫秒没有被解析到字符串中。
所以我的问题是,我怎样才能使我的测试工作,有没有办法检查用 with 调用的参数是否在当前时间的 x 毫秒内?
试试这个:
var spy = spyOn(mockSock, 'getComments').and.callThrough();
var today = moment('2017-4-29').toDate();
jasmine.clock().mockDate(today);
expect(spy.calls.mostRecent().args[0]).toEqual('api/jobs/604');
expect(spy.calls.mostRecent().args[1].valueOf()).toEqual(today.valueOf());
参考:https://jasmine.github.io/2.5/introduction.html#section-Jasmine_Clock
我在 angular (4) -
中进行了以下测试 it('should call service',
async(inject([CommentTableComponent], (cmp: CommentTableComponent) => {
spyOn(mockSock, 'getComments').and.callThrough();
cmp.ngOnInit();
expect(mockSock.getComments).toHaveBeenCalledWith('api/jobs/604', moment());
})));
抛出错误:
Expected spy getComments to have been called with [ 'api/jobs/604', Sat Apr 29 2017 12:31:07 GMT+0100 ] but actual calls were [ 'api/jobs/604', Sat Apr 29 2017 00:00:00 GMT+0100, Sat Apr 29 2017 12:31:07 GMT+0100 ].
因为这些字符串显然是相同的,我假设这是因为 now 的测试值比组件 运行 时的值晚了几毫秒,并且这些毫秒没有被解析到字符串中。
所以我的问题是,我怎样才能使我的测试工作,有没有办法检查用 with 调用的参数是否在当前时间的 x 毫秒内?
试试这个:
var spy = spyOn(mockSock, 'getComments').and.callThrough();
var today = moment('2017-4-29').toDate();
jasmine.clock().mockDate(today);
expect(spy.calls.mostRecent().args[0]).toEqual('api/jobs/604');
expect(spy.calls.mostRecent().args[1].valueOf()).toEqual(today.valueOf());
参考:https://jasmine.github.io/2.5/introduction.html#section-Jasmine_Clock