在AngularJS嘲讽日期/茉莉花测试 [英] Mocking dates in AngularJS / Jasmine tests

查看:147
本文介绍了在AngularJS嘲讽日期/茉莉花测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个初始化Date对象多次在若干功能的指令。
当单元测试的各个功能我可以处理存根日期是这样的:

I have a directive that initializes the Date object several times in several functions. When Unit testing the individual functions I can handle stubbing the date like this:

(function (global) {
  var NativeDate = global.Date;

  global.stubDateConstructor = function (fakeDate) {
      global.Date = function () {
          global.Date = NativeDate;
          return fakeDate;
      }
  }
}(this));

// ageInYears()
it("should return the age in years of the person given his/her birthdate", function() {
    stubDateConstructor(new Date('2010/01/01'));
    expect(ageInYears('01-01-1990')).toBe(20);
    stubDateConstructor(new Date('2010/01/01'));
    expect(ageInYears('01-01-1900')).toBe(110);
});

有关单元测试指令本身,它调用ageInYears和其他一些类似的功能,这不会调用一次日后为我工作()stubDateConstructor将重置日期()到真正的Date对象。

For unittesting the directive itself, which calls the ageInYears and several other similar functions this isn't going to work as I after one call to Date() stubDateConstructor will have reset Date() to the real Date object.

有没有AngularJS /茉莉花本机的方式来处理这些情况,还是应该考虑兴农例如?

Is there a native way in AngularJS / Jasmine to handle these situations, or should I look into Sinon e.g.?

推荐答案

茉莉花(2.2)时钟可以模拟日期和时间。

Jasmine (2.2) Clock can mock dates and time.

<一个href=\"http://jasmine.github.io/2.2/introduction.html#section-Mocking_the_Date\">http://jasmine.github.io/2.2/introduction.html#section-Mocking_the_Date

例如(从文档):

it("mocks the Date object and sets it to a given time", function() {
  var baseTime = new Date(2013, 9, 23);
  jasmine.clock().mockDate(baseTime);

  jasmine.clock().tick(50);
  expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
});

这篇关于在AngularJS嘲讽日期/茉莉花测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆