【问题标题】:Jasmine date mocking with moment.js用 moment.js 模拟茉莉花日期
【发布时间】:2015-10-27 23:28:26
【问题描述】:

我在我的应用程序中使用 moment.js 作为日期/时间,但它似乎不能很好地与 Jasmine 的模拟功能配合使用。我在下面整理了一个测试套件来显示我的问题:

jasmine.clock().mockDate 似乎暂时无法正常工作,而 Date 可以正常工作。

describe('Jasmine tests', function () {
    beforeEach(function() {
        jasmine.clock().install();
    });

    afterEach(function() {
        jasmine.clock().uninstall();
    });

    // Pass
    it('uses the mocked time with Date', function() {
        var today = new Date('2015-10-19');
        jasmine.clock().mockDate(today);
        expect(new Date().valueOf()).toEqual(today.valueOf());
    });


    // Fail
    it('uses the mocked time with moment', function() {
        var today = moment('2015-10-19');
        jasmine.clock().mockDate(today);

        expect(moment().valueOf()).toEqual(today.valueOf());
    });
});

为什么Date 能按预期工作,而moment 不能? moment 不是在后台使用 Date 吗?

使用 Jasmine 模拟 moment 的正确方法是什么?

【问题讨论】:

    标签: javascript jasmine momentjs


    【解决方案1】:

    jasmine.clock().mockDate 期望 Date 作为输入。 Datemoment 不完全兼容。如果您在规范本身中提供要模拟的日期,您可以简单地使用 Date 代替。

    如果您的代码生成了您想要模拟的时刻,或者您更愿意使用时刻 API,请查看 moment.toDate()。该方法返回Date 对象。

    it('uses the mocked time with moment', function() {
        var today = moment('2015-10-19').toDate();
        jasmine.clock().mockDate(today);
        expect(moment().valueOf()).toEqual(today.valueOf());
    });
    

    【讨论】:

    • 重要提示 - 不要忘记在测试后重置模拟日期! AFAIK,调用 jasmine.clock().mockDate(..) 是一个全局操作,因此最好在单独的 beforeEach 块中设置(和取消设置)它。然后稍后在 afterEach 块中使用 jasmine.clock().uninstall() 清除它。
    • 谢谢!像魅力一样工作
    • 似乎 jasmine.clock().mockDate() 还更新了我没想到的先前生成的时刻。此测试显示问题:it('should not mess up a previously stored time', () => { var initial = moment(); var newTime = initial.add({ minutes: 5 }).toDate(); jasmine.clock().mockDate(newTime); var final = moment(); expect(final).not.toEqual(initial); });
    【解决方案2】:

    查看 moment mock 如何在他们自己的测试套件中约会自己: https://github.com/moment/moment/blob/2e2a5b35439665d4b0200143d808a7c26d6cd30f/src/test/moment/now.js#L15

    【讨论】:

      【解决方案3】:

      我试图找到jasmine 甚至其他模拟框架的替代方案来避免依赖

      const currentToday = moment().toDate();
      console.log(`currentToday:`, currentToday)
      
      const newToday = moment('1980-01-01').toDate();
      console.log(`newToday    :`, newToday);
      
      Date.now = () => {
        return newToday
      };
      
      const fakedToday = moment().toDate();
      console.log(`fakedToday  :`, fakedToday)
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
      currentToday: 2019-09-17T15:26:12.763Z
      newToday    : 1980-01-01T00:00:00.000Z
      fakedToday  : 1980-01-01T00:00:00.001Z
      

      【讨论】:

        【解决方案4】:
        1. 导入时刻到规范文件

          import * as moment from 'moment';

        2. 立即期待您的测试用例

          const stringDate = moment.utc(date).format(stringFormat); 期望(stringDate).toEqual('2021-05-23T08:00:00');

        3. 最终的规范文件如下所示

        import { TestBed } from '@angular/core/testing';
        import { convertDateToString, getDateDifferenceInHours, getDateIsoStringWithoutTimezone, getDateIsoStringWithTimezone, getDateWithoutTimezone } from './DateHelper';
        import * as  moment from 'moment';
        import * as DateHelper from '@shared/helper/DateHelper';
        
        describe('DateHelper', () => {
          beforeEach(async () => {
            await TestBed.configureTestingModule({
            });
          });
        
          it('should convert date to string YYYY-MM-DD', () => {
            expect(convertDateToString(new Date('05-23-2021 12:00'), 'YYYY-MM-DD')).toEqual('2021-05-23');
          });
        
          it('should convert date to iso string without timezone', () => {
            expect(getDateIsoStringWithoutTimezone(new Date('05-23-2021 12:00'))).toEqual('2021-05-23T12:00:00.000Z');
          });
        
        });

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-12
          相关资源
          最近更新 更多