Jasmine .toHaveBeenCalledWith(aDate)无法正常工作

3

我正在继承一些代码,其中有两个测试仍然失败,不确定它们以前是否失败过,或者是因为我使用了不同版本的Jasmine(它们是在2.0之前编写的)。

在beforeEach中设置了这个spy,导致测试失败。

spyOn(datacontext, 'getImportLogForDate').and.callThrough();

在测试中,需要进行以下步骤:
controller.DepositDate = new Date();
controller.PerformActionThatCallsGetImportLogForDate();
expect(context.getImportLogForDate).toHaveBeenCalledWith('1', controller.DepositDate);

由于它们完全相同,因此产生的错误令人困惑

期望调用间谍函数 getImportLogForDate 时传入 [ '1', Date(Thu Dec 04 2014 13:00:51 GMT-0600 (Central Standard Time)) ] ,但实际调用为 [ '1', Date(Thu Dec 04 2014 13:00:51 GMT-0600 (Central Standard Time)) ]

我不能验证函数是否已使用日期进行调用吗?

2个回答

7

PerformActionThatCallsGetImportLogForDate这个函数是如何处理日期对象的?Jasmine会通过毫秒值来比较日期对象,所以即使相差1毫秒,它们也不会相等,但你在控制台输出中看不到这种细节。

或者,你可以选择另外两个选项。

只需测试第二个参数是否为日期对象。

expect(context.getImportLogForDate)
    .toHaveBeenCalledWith('1', jasmine.any(Date));

测试日期值,但在toHaveBeenCalledWith之外进行,以防该匹配器存在某些特定的奇怪情况。

expect(context.getImportLogForDate.calls.mostRecent().args[0])
    .toEqual('1');
expect(context.getImportLogForDate.calls.mostRecent().args[1])
    .toEqual(controller.DepositDate);

2

我发现在使用 toHaveBeenCalledWith 来针对特定的 Date 时,jasmine.objectContaining 非常好用。

it('#userChangedMonth calls fetchData with end of month', () => {
    spyOn(component, 'fetchData').and.returnValue(true);
    const calendarChangedTo = new Date('2018-10-10 00:00:00');
    const endOfMonth = new Date('2018-10-31 23:59:59');
    component.userChangedMonth(calendarChangedTo);
    expect(component.fetchData).toHaveBeenCalledWith(jasmine.objectContaining(endOfMonth));
  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接