【问题标题】:SpyOn and return typeof undefined object in JasmineSpyOn 并返回 Jasmine 中未定义的对象类型
【发布时间】:2014-02-07 00:25:17
【问题描述】:

我有一个在 IE8 中失败的脚本,因为 Date.now() 未定义。我已将 Date.now() 抽象为一个方法并想对其进行单元测试,我知道它在 Date.now() 未定义时是否有效。

Foo.prototype = {
  date: function() {
    // I think this works. Not sure until I get my unit test working...
    if (typeof Date.now === 'undefined') {
      Date.now = function () { return +new Date(); }
    }
    return Date.now(); // fails in IE8. Undefined.
  }
}

我的测试是这样的

describe('Foo', function() {
  it('has the current date time', function() {
    // This passes
    spyOn(Date, 'now').and.returnValue(1234);
    foo = new Foo;
    expect(foo.date()).toBe(1234);
  });

  it('has the current date time for IE8', function() {
    // This won't pass
    spyOn(Date, 'now').and.returnValue(null);
    foo = new Foo;
    expect(foo.date()).toBe(1234); // TODO
  });
});

如何存根未定义?我正在考虑在 returnValue 中返回一个未定义的方法。

我知道我的测试并没有完善,因为我才刚刚开始使用 Jasmine。

【问题讨论】:

    标签: unit-testing tdd jasmine


    【解决方案1】:

    您不能监视未定义的函数。 你可以这样做:

      it('has the current date time for IE8', function() {
        // This won't pass
          var x = Date.now;
          Date.now = undefined;
        foo = new Foo;
        expect(foo.date()).toBe(1234); // TODO
          Date.now = x;
      });
    

    【讨论】:

      【解决方案2】:

      问题是间谍的行为仍然像一个函数,但是当您测试它是否存在时,您实际上并没有调用该方法。当您 spyOn(Date, 'now') 时,您正在用一个间谍对象替换内置的 Date.now 函数。如果你做了这样的事情:

      describe('Foo', function() {
        describe("without a Date.now", function() {
          beforeEach(function() {
            this.now = Date.now;
            Date.now = undefined;
          });
      
          afterEach(function() {
            Date.now = this.now;
          });
      
          it('has the current date time for IE8', function() {
            spyOn(window, 'Date').and.returnValue(1234);
            foo = new Foo;
            expect(foo.date()).toBe(1234); // TODO
          });
        });
      });
      

      typeof 检查将成功,您的代码会将 Date.now 函数设置为您的新实现。由于这不是茉莉花间谍,您必须自己清理(因此afterEach)。这个规范仍然没有完全通过,因为它没有完全正确地存根 Date 构造函数。

      【讨论】:

        猜你喜欢
        • 2016-05-12
        • 1970-01-01
        • 2015-08-22
        • 2014-12-21
        • 1970-01-01
        • 1970-01-01
        • 2019-12-15
        • 2017-07-11
        • 1970-01-01
        相关资源
        最近更新 更多