【问题标题】:Using jasmie .toHaveBeenCalledWith() function with Moment Objects将 jasmie .toHaveBeenCalledWith() 函数与 Moment 对象一起使用
【发布时间】:2017-09-27 11:14:16
【问题描述】:

我在角度 (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());
    })));

引发错误:

预计 spy getComments 已被调用 ['api/jobs/604', Sat Apr 29 2017 12:31:07 GMT+0100] 但实际调用是 ['api/jobs/604', Sat Apr 29 2017 00:00:00 GMT+0100,2017 年 4 月 29 日星期六 12:31:07 GMT+0100]。

由于这些字符串显然是相同的,我认为这是因为 now 的测试值比组件运行时的值晚了几毫秒,并且毫秒没有被解析到字符串中。

所以我的问题是,我怎样才能使我的测试工作,有没有办法在当前时间的 x 毫秒内检查调用的参数?

【问题讨论】:

    标签: angular typescript jasmine karma-runner momentjs


    【解决方案1】:

    试试这个:

    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

    【讨论】:

    • Property 'calls' does not exist on type '(uri: any, startT: any, endT: any) => Observable<IJobResp[]>'. ?
    • 在你spyOn(mockSock, 'getComments')之后你只有calls
    • 嗯,Typescript 编译器失败了,即使在间谍之后,我的测试也没有运行并出现上述错误
    • 你安装了@types/jasmine 包吗?或者你可以(mockSock.getComments as any).calls.mostRecent...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 2017-02-08
    • 2017-06-07
    • 2020-08-04
    • 2021-04-02
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多