无法单元测试原型方法

时间:2016-02-25 17:13:17

标签: javascript unit-testing jasmine

我有一个对象,我正在尝试使用Jasmine对其中一个方法进行单元测试。我得到的错误是undefined is not a function (evaluation foo.initArr())

foo.js

function Foo(value) {
  if(typeof value !== "string") {
    value = "";
  }

  var foo = {
    value: value
  };

  return foo;
};

Foo.prototype.initArr = function(arr) {
  if(arr) {
    // do nothing
  } else {
    // initialize array
    arr = [];
  }

  return arr;
};

foo.spec.js

describe("foo.js", function() {
  var validVal,
    numberVal,
    nullVal,
    falseVal,
    trueVal,
    undefinedVal;

  beforeEach(function() {
    validVal = "PrQiweu";
    numberVal = 420;
    nullVal = null;
    falseVal = false;
    trueVal = true;
    undefinedVal = undefined;
  });

  afterEach(function() {
    validVal = null;
    numberVal = null;
    falseVal = null;
    trueVal = null;
    undefinedVal = null;
  });

  describe("Foo:constructor", function() {
    it("should return an empty string if the passed value isn't a string", function() {
      var foo = new Foo(numberVal);
      expect(foo.value).toEqual("");
    });

    it("should return a string if the passed value is a string", function() {
      var foo = new Foo(validVal);
      expect(foo.value).toEqual(jasmine.any(String));
    });

    describe("method:arr", function() {

      it("should return an empty array if it wasn't passed one", function() {
        var foo = new Foo(validVal);
        expect(foo.initArr()).toBe([]);        
      });
    })
  });
});

最后一个测试用例失败了。我认为这里也不需要间谍,但我可能错了。我意识到initArr函数毫无意义,所以请忽略我的白痴。

为什么最后一个测试用例失败了,我该如何解决呢?

1 个答案:

答案 0 :(得分:3)

你的构造函数返回一个不同的 foo ,它没有原型函数。

function Foo(value) {
  if(typeof value !== "string") {
    value = "";
  }

  var foo = {
    value: value
  };

  return foo;  // This foo your locally defined foo var, 
};

也许你打算写这个:

function Foo(value) {
  if(typeof value !== "string") {
    value = "";
  }
  this.value = value;
};
相关问题