用Jasmine模拟日期构造函数 [英] Mock date constructor with Jasmine

查看:167
本文介绍了用Jasmine模拟日期构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个将日期作为可选参数的函数。我想声明如果在没有参数的情况下调用函数,就会创建一个新的Date对象。

I'm testing a function that takes a date as an optional argument. I want to assert that a new Date object is created if the function is called without the argument.

var foo = function (date) {
  var d = date || new Date();
  return d.toISOString();
}

如何断言新日期被叫?

到目前为止,我有这样的事情:

So far, I've got something like this:

it('formats today like ISO-8601', function () {
  spyOn(Date, 'prototype');
  expect().toHaveBeenCalled();
});

参见: https://github.com/pivotal/jasmine/wiki/Spies

推荐答案

归功于@ HMR。我写的测试验证:

Credit to @HMR. Test I wrote to verify:

  it('Should spy on Date', function() {
    var oldDate = Date;
    spyOn(window, 'Date').andCallFake(function() {
      return new oldDate();
    });
    var d = new Date().toISOString;
    expect(window.Date).toHaveBeenCalled();
  });

这篇关于用Jasmine模拟日期构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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